Arrays in Java allow you to store multiple values of the same data type in a single variable. They are very useful data structures that can organize your data and make it easier to access.

There are a few different ways to initialize arrays in Java:

  1. Declare an array variable without allocating memory
  2. Allocate memory using new and initialize with defaults
  3. Initialize array with values using an array initializer
  4. Initialize array element-by-element

Let‘s explore each approach in more detail.

Declare an Array Variable

You can declare an array variable by specifying the type followed by square brackets []:

int[] numbers;
String[] names; 
MyClass[] objects;

This syntax declares a variable that can hold an array, but does not actually create the array or allocate memory for it.

For example:

int[] numbers;
numbers[0] = 5; // ERROR! Array not initialized

This would result in a NullPointerException because the array does not point to a valid memory location yet.

So array declaration only defines the variable itself, not the actual array contents.

Allocate Memory with new

We can allocate memory for an array and initialize elements to default values using the new keyword:

int[] numbers = new int[5];

This allocates an array of 5 integers and sets each element to the default value 0.

We can print out the contents to see the default initialization:

int[] numbers = new int[5];
for(int i = 0; i < numbers.length; i++) {
  System.out.println(numbers[i]); 
}

// Output: 
0
0
0  
0
0

Similarly, reference types like Strings will be initialized to null by default:

String[] names = new String[3];
for(String name : names) {
  System.out.println(name);
} 

// Output:
null
null
null

So new is useful for allocating memory with default values. But often we want to initialize elements to other values.

Initialize with Array Initializer

We can initialize an array with specific values using an array initializer:

int[] numbers = {1, 2, 3, 4}; 
String[] names = {"John", "Sarah", "Mary"};

This creates the array with the given values inserted into each index.

We can print them out to confirm:

int[] numbers = {1, 2, 3, 4};
for(int number : numbers) {
  System.out.println(number);
}

// Output:
1
2  
3
4

This is useful for initializing arrays inline without having to set each index individually.

Some key notes about array initializers:

  • The length is determined automatically by the number of values between { and }
  • Can be used to initialize part of an array, leaving the rest as default values

For example:

int[] numbers = new int[5]; 
numbers = {1, 2, 3}; // Length 3 

int[] otherNumbers = {1, 2, 3, 0, 0}; // Length 5

So array initializers provide an easy way to define array values at creation time.

Initialize Element-by-Element

The last approach we‘ll cover is to initialize array elements one-by-one:

String[] names = new String[3];
names[0] = "John"; 
names[1] = "Sarah";
names[2] = "Mary";

This allows you to declare the array first, then set each index later.

The same print out code would work to verify the values:

for(String name : names) {
  System.out.println(name); 
}

// Output:  
John
Sarah
Mary

Some other examples in different data types:

int[] numbers = new int[4];
numbers[0] = 1;
numbers[1] = numbers[0] + 2; // read values from other indexes
numbers[2] = squared(5); // method call
numbers[3] = random.nextInt(10); //random value

boolean[] bools = new boolean[2]; 
bools[0] = true;
bools[1] = !bools[0]; // set based on other values

String[] objects = new MyObject[5];
objects[0] = new MyObject(); // call constructor 
for(int i = 1; i < objects.length; i++) {
  objects[i] = new MyObject(i); 
}

This approach allows full control over initializing values, with the ability to read other elements in the array, call methods, generate random values, etc.

The downside is it can be more verbose than array initializers if initializing a lot of data.

Summary

In summary, here are the main approaches to initialize arrays in Java:

  1. Array declaration – Define the variable itself
  2. Allocate with new – Creates array with default values
  3. Array initializer – Inline syntax for initializing values
  4. Element-by-element – Flexibility to set each index separately

The choice depends on your specific use case. Small arrays with simple values are easy to define with initializers. Larger datasets may be better suited to programmatic allocation and element assignment.

Arrays are a critical building block in Java. Understanding initialization helps set a solid foundation for leveraging arrays in your codebase for organizing and storing data.

Similar Posts