1. The Hook (The "Byte-Sized" Intro)
- In a Nutshell: Array initialization populates arrays with values.
- Three methods: static (at declaration), dynamic (loop/input), and block (computed values).
When Netflix pre-loads trending shows: String[] trending = {"Show1", "Show2", ...}. Static init—values known upfront!
2. Conceptual Clarity
💡 The Analogy: Stocking Shelves
- Static init = Shelves arrive pre-stocked (known products)
- Dynamic init = Fill shelves based on daily deliveries (runtime data)
- Block init = Calculate what goes where (computed placement)
3. Technical Mastery
Three Initialization Methods
graph TB
Init["Array Initialization"] --> Static["Static<br/>{1,2,3}"]
Init --> Dynamic["Dynamic<br/>Loop/Input"]
Init --> Computed["Computed<br/>Formula-based"]
style Static fill:#2E7D32
style Dynamic fill:#F57C00
style Computed fill:#1976D2
4. Interactive & Applied Code
java
public class ArrayInitialization {
public static void main(String[] args) {
// === STATIC INITIALIZATION ===
// Values known at compile time
int[] primes = {2, 3, 5, 7, 11};
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
double[] prices = {9.99, 19.99, 29.99};
// === DYNAMIC INITIALIZATION ===
// Values determined at runtime
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i * 10; // 0, 10, 20, 30, 40
}
// From user input
java.util.Scanner sc = new java.util.Scanner(System.in);
int[] userScores = new int[3];
for (int i = 0; i < userScores.length; i++) {
System.out.print("Enter score " + (i+1) + ": ");
userScores[i] = sc.nextInt();
}
// === COMPUTED INITIALIZATION ===
// Values calculated by formula
int[] squares = new int[10];
for (int i = 0; i < squares.length; i++) {
squares[i] = i * i; // 0, 1, 4, 9, 16, 25, 36, 49, 64, 81
}
// Fibonacci sequence
int[] fib = new int[10];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
// === PARTIAL INITIALIZATION ===
int[] partial = new int[5];
partial[0] = 100;
partial[2] = 200;
// partial[1], [3], [4] remain 0 (default)
// === ANONYMOUS ARRAY ===
printSum(new int[]{10, 20, 30}); // Inline creation
}
static void printSum(int[] arr) {
int sum = 0;
for (int n : arr) sum += n;
System.out.println("Sum: " + sum);
}
}⚠️ Common Mistakes
Mistake #1: Can't use static init after declaration
java
int[] arr;
arr = {1, 2, 3}; // ❌ Compile error!
// Must use: arr = new int[]{1, 2, 3};Mistake #2: Size mismatch
java
int[] arr = new int[5];
arr = {1, 2, 3}; // ❌ Can't reassign with static init5. The "Interview Corner"
🏆 Q1: "Difference: int[] a = {1,2} vs int[] a = new int[]{1,2}?"
Answer: Same result, but new int[] required for anonymous/inline arrays or reassignment.
🏆 Q2: "What if array partially initialized?" Answer: Unset elements get default values (0 for int, null for objects).
🎓 Key Takeaways
✅ Static: {1,2,3} when values known
✅ Dynamic: Loop when values computed/input
✅ Anonymous: new int[]{...} for inline use
✅ Partial init → defaults fill gaps