Bird
Raised Fist0
DSA Javaprogramming

Array Declaration and Initialization in DSA Java

Choose your learning style10 modes available
Mental Model
An array is a fixed-size collection of items stored next to each other in memory, where each item can be accessed by its position number.
Analogy: Think of an array like a row of mailboxes, each with a number. You can put a letter in any mailbox or take it out by knowing its number.
Index:  [0] -> [1] -> [2] -> [3] -> [4]
Value:  [ ]   [ ]   [ ]   [ ]   [ ]
Dry Run Walkthrough
Input: Declare an integer array of size 5 and initialize it with values 10, 20, 30, 40, 50
Goal: Create an array that holds these 5 numbers in order and can be accessed by their positions
Step 1: Declare an integer array variable named arr with size 5
Index:  [0] -> [1] -> [2] -> [3] -> [4]
Value:  [ ]   [ ]   [ ]   [ ]   [ ]
Why: We need to reserve space for 5 integers before storing values
Step 2: Assign value 10 to arr[0]
Index:  [0] -> [1] -> [2] -> [3] -> [4]
Value:  [10]  [ ]   [ ]   [ ]   [ ]
Why: Store the first number at the first position
Step 3: Assign value 20 to arr[1]
Index:  [0] -> [1] -> [2] -> [3] -> [4]
Value:  [10]  [20]  [ ]   [ ]   [ ]
Why: Store the second number at the second position
Step 4: Assign value 30 to arr[2]
Index:  [0] -> [1] -> [2] -> [3] -> [4]
Value:  [10]  [20]  [30]  [ ]   [ ]
Why: Store the third number at the third position
Step 5: Assign value 40 to arr[3]
Index:  [0] -> [1] -> [2] -> [3] -> [4]
Value:  [10]  [20]  [30]  [40]  [ ]
Why: Store the fourth number at the fourth position
Step 6: Assign value 50 to arr[4]
Index:  [0] -> [1] -> [2] -> [3] -> [4]
Value:  [10]  [20]  [30]  [40]  [50]
Why: Store the fifth number at the fifth position
Result:
Index:  [0] -> [1] -> [2] -> [3] -> [4]
Value:  [10]  [20]  [30]  [40]  [50]
Annotated Code
DSA Java
public class ArrayExample {
    public static void main(String[] args) {
        // Step 1: Declare an integer array of size 5
        int[] arr = new int[5];
        
        // Step 2-6: Initialize array elements
        arr[0] = 10; // assign 10 to first element
        arr[1] = 20; // assign 20 to second element
        arr[2] = 30; // assign 30 to third element
        arr[3] = 40; // assign 40 to fourth element
        arr[4] = 50; // assign 50 to fifth element
        
        // Print the array elements
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            if (i < arr.length - 1) {
                System.out.print(" -> ");
            }
        }
        System.out.print(" -> null\n");
    }
}
int[] arr = new int[5];
Reserve space for 5 integers in memory
arr[0] = 10;
Store 10 at first position
arr[1] = 20;
Store 20 at second position
arr[2] = 30;
Store 30 at third position
arr[3] = 40;
Store 40 at fourth position
arr[4] = 50;
Store 50 at fifth position
for (int i = 0; i < arr.length; i++) {
Traverse array from start to end to print values
System.out.print(arr[i]);
Print current element value
OutputSuccess
10 -> 20 -> 30 -> 40 -> 50 -> null
Complexity Analysis
Time: O(n) because we initialize and print each of the n elements once
Space: O(n) because the array stores n elements in contiguous memory
vs Alternative: Compared to using individual variables, arrays use less code and allow easy access by index
Edge Cases
Declare array with size zero
Array is created with no elements; accessing any index causes error
DSA Java
int[] arr = new int[0];
Access index outside array bounds
Throws ArrayIndexOutOfBoundsException at runtime
DSA Java
for (int i = 0; i < arr.length; i++) {
When to Use This Pattern
When you need to store multiple items of the same type in order and access them by position, use arrays because they provide fixed-size indexed storage.
Common Mistakes
Mistake: Trying to access or assign values outside the declared array size
Fix: Always use indices from 0 up to array length minus one to avoid errors
Mistake: Forgetting to initialize array elements before use
Fix: Assign values to each element before reading them to avoid default zero or unexpected values
Summary
An array holds multiple values of the same type in a fixed-size sequence accessible by index.
Use arrays when you want to group related data items and access them quickly by position.
Remember arrays reserve space upfront and use zero-based indexing to find each element.

Practice

(1/5)
1. Which of the following is the correct way to declare and initialize an integer array of size 5 in Java?
easy
A. int[] arr = new int[5];
B. int arr = new int[5];
C. int arr[] = int[5];
D. int[] arr = int[5];

Solution

  1. Step 1: Understand Java array declaration syntax

    In Java, arrays are declared with the type followed by square brackets and initialized with the new keyword and size inside square brackets.
  2. Step 2: Check each option for correct syntax

    int[] arr = new int[5]; uses correct syntax: int[] arr = new int[5]; Options A, B, and D have syntax errors or missing keywords.
  3. Final Answer:

    int[] arr = new int[5]; -> Option A
  4. Quick Check:

    Correct Java array declaration = int[] arr = new int[5]; [OK]
Hint: Use 'new' keyword and specify size in brackets [OK]
Common Mistakes:
  • Forgetting 'new' keyword
  • Using wrong brackets or missing type
  • Declaring array without brackets
2. Which of the following is a valid way to declare and initialize an array with values in Java?
easy
A. int[] arr = new int[] {1, 2, 3, 4};
B. int arr[] = new int{1, 2, 3, 4};
C. int[] arr = new int{1, 2, 3, 4};
D. int arr = {1, 2, 3, 4};

Solution

  1. Step 1: Understand array initialization with values

    In Java, to initialize an array with values using 'new', syntax is: int[] arr = new int[] {values};
  2. Step 2: Check each option

    int[] arr = new int[] {1, 2, 3, 4};: correct syntax. int arr[] = new int{1, 2, 3, 4};: incorrect declaration style and missing [] after new int. int[] arr = new int{1, 2, 3, 4};: missing [] after new int. int arr = {1, 2, 3, 4};: arr not declared as array.
  3. Final Answer:

    int[] arr = new int[] {1, 2, 3, 4}; -> Option A
  4. Quick Check:

    Array init with 'new int[]' = int[] arr = new int[] {1, 2, 3, 4}; [OK]
Hint: Use 'new int[]' when initializing separately [OK]
Common Mistakes:
  • Omitting 'new' when required
  • Using wrong brackets
  • Assigning values without array type
3. What will be the output of the following Java code?
int[] arr = new int[3];
arr[0] = 5;
arr[2] = 10;
System.out.println(arr[1]);
medium
A. 5
B. 0
C. 10
D. Compilation error

Solution

  1. Step 1: Understand default values in integer arrays

    When an integer array is created with 'new int[3]', all elements are initialized to 0 by default.
  2. Step 2: Check assigned values and output

    arr[0] = 5 and arr[2] = 10 are assigned. arr[1] is not assigned, so it remains 0. The print statement outputs arr[1], which is 0.
  3. Final Answer:

    0 -> Option B
  4. Quick Check:

    Unassigned int array element = 0 [OK]
Hint: Unassigned int array elements default to 0 [OK]
Common Mistakes:
  • Assuming unassigned elements have garbage values
  • Confusing index positions
  • Expecting runtime error for unassigned index
4. Identify the error in the following Java array declaration:
int arr[5];
medium
A. Missing semicolon at the end
B. Array must be declared with curly braces
C. Array size cannot be specified in declaration without initialization
D. Array size must be a variable, not a number

Solution

  1. Step 1: Understand Java array declaration rules

    In Java, you cannot specify the size of the array in the declaration alone. Size must be specified during initialization with 'new'.
  2. Step 2: Analyze the given code

    int arr[5]; tries to declare an array with size 5 without initialization, which is invalid syntax in Java.
  3. Final Answer:

    Array size cannot be specified in declaration without initialization -> Option C
  4. Quick Check:

    Size only with 'new' keyword [OK]
Hint: Specify size only with 'new' keyword during initialization [OK]
Common Mistakes:
  • Using C-style array declaration
  • Trying to declare size without 'new'
  • Confusing declaration and initialization
5. Given the following code, what will be the output?
int[] arr = {1, 2, 3};
arr = new int[] {4, 5};
System.out.print(arr.length);

Choose the correct output and explain why.
hard
A. 3
B. Runtime error
C. Compilation error
D. 2

Solution

  1. Step 1: Understand array reassignment

    Initially, arr points to an array of length 3 with values {1, 2, 3}. Then arr is reassigned to a new array with values {4, 5} of length 2.
  2. Step 2: Check the length property after reassignment

    After reassignment, arr.length reflects the new array length, which is 2.
  3. Final Answer:

    2 -> Option D
  4. Quick Check:

    Array length after reassignment = 2 [OK]
Hint: Array variable can point to new array; length updates accordingly [OK]
Common Mistakes:
  • Assuming original array length remains
  • Expecting error on reassignment
  • Confusing array contents with length
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard