How do I declare and initialize an array in Java?

In Java, you can declare and initialize arrays in several ways depending on your needs. Here’s a concise guide with examples:

1. Declare and Initialize Separately

Step 1: Declare the Array

// Syntax: type[] arrayName;
int[] numbers;      // For primitives (e.g., int, double)
String[] names;     // For objects (e.g., String, custom classes)

Step 2: Initialize with Fixed Size

Use new to allocate memory and set a fixed size:

numbers = new int[5];       // Array of 5 integers (default: 0)
names = new String[3];      // Array of 3 Strings (default: null)

2. Declare and Initialize in One Line

With Explicit Values

int[] numbers = {10, 20, 30, 40, 50};  // Size inferred from values
String[] names = {"Alice", "Bob", "Charlie"};

Using new Keyword

int[] numbers = new int[]{10, 20, 30}; // Explicit initialization
String[] names = new String[]{"Alice", "Bob"};

3. Initialize with Default Values

Elements are set to default values (e.g., 0, false, null):

boolean[] flags = new boolean[3];  // [false, false, false]
Integer[] values = new Integer[4]; // [null, null, null, null]

4. Multi-Dimensional Arrays

Rectangular 2D Array

int[][] matrix = new int[3][3];  // 3x3 grid (all rows same length)
matrix[0][0] = 1;               // Assign a value

Jagged Array (Rows of Different Lengths)

int[][] jagged = new int[2][];   // 2 rows
jagged[0] = new int[3];         // First row has 3 elements
jagged[1] = new int[5];         // Second row has 5 elements

Initialize with Values

int[][] matrix = {{1, 2}, {3, 4}, {5, 6}}; // 3x2 array
String[][] grid = {{"A", "B"}, {"C"}};     // Jagged array

Key Notes

  • Fixed Size: Once initialized, the array length cannot change.
  • Indexing: Access elements via array[index] (indices start at 0).
  • Common Errors:
  • ArrayIndexOutOfBoundsException: Accessing an invalid index.
  • Incorrect initialization:
    int[] arr = new int[3]{1, 2, 3}; (Size and values conflict)
    int[] arr = new int[]{1, 2, 3}; or int[] arr = {1, 2, 3};

Example: Iterating Over an Array

int[] numbers = {10, 20, 30};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}
// Output: 10, 20, 30

// Enhanced for-loop (Java 5+)
for (int num : numbers) {
    System.out.println(num);
}

Useful Methods

  • Copy Arrays:
  int[] copy = Arrays.copyOf(numbers, numbers.length);
  • Sort:
  Arrays.sort(numbers);
  • Print:
  System.out.println(Arrays.toString(numbers)); // [10, 20, 30]

Choose the method that best fits your use case!

Leave a Reply

Your email address will not be published. Required fields are marked *