How to Declare and Initialize an Array in Java

Learn to declare and initialize arrays using different techniques and their differences. Apart from directly accessing the arrays, we will also be using the java.util.Arrays and Stream API that provides several useful methods to work with arrays in Java.

Note that an array is a contiguous block of memory so it is mandatory to mention the length or size of the array during the initialization. Later, we can add the items in the array at the specified indices.

Also, it is worth recalling that array indices always start from 0. The first element of an array is at index 0. If the size of an array is n, then the last element of the array will be at index n-1.

1. Initializing Array at Time of Declaration

Declaring and initializing an array in a single statement (array initializer) is a good idea if:

  • We know the array of items in advance
  • Array size is small
String status[] = new String[] { 
	"Active", "Inactive", "Purged" };

Note that the type information is optional when initializing the array at the time of declaration.

String status[] = { "Active", "Inactive", "Purged" };

The type information is mandatory if we attempt to initialize an array after it has been declared, otherwise, we will get the compilation error “Array constants can only be used in initializers“.

String status[] = new String[3];
// This is not compile
//status = {"Active", "Inactive", "Purged" };

2. Populating Array in Loop

This approach is useful when filling the array one at a time. The easiest way is to loop through array indices and put the desired item in the specified index location.

int nums[] = new int[5];

for (int i = 0; i < nums.length; i++) {
    nums[i] = i;
}

3. Arrays.fill() API

The fill() method takes a value and assigns the specified value to each element of the specified array. In the given example, we are filling all the array elements with 1.

int numbers[] = new int[10];

Arrays.fill(numbers, 1);  //[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

Note that the fill() is an overloaded method and can take the start and the end index upto which the array must be filled. In the given example, we are filling the array from index positions 2 to 9.

int numbers[] = new int[10];

Arrays.fill(numbers, 2, 9, 1); //[0, 0, 1, 1, 1, 1, 1, 1, 1, 0]

4. Arrays.setAll() API

The setAll() sets all elements of the array, using the provided generator function to compute each element.

int[] squares = new int[6];

Arrays.setAll(squares, p -> p * p);	//[0, 1, 4, 9, 16, 25]

Note that any exception thrown by the generator function is relayed to the caller and the array is left in an indeterminate state.

5. Using Streams

Java streams API provides many inbuilt classes that can generate streams and support sequential and parallel aggregate operations on those streams. IntStream, LongStream and DoubleStream are examples of such streams.

int[] intArray = IntStream.range(1, 11).toArray();
int[] intArray = IntStream.rangeClosed(1, 10).toArray();
int[] intArray = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).toArray();

6. Arrays.copyOf() and Arrays.copyOfRange()

The copyOf() method is super useful if we want a new array containing the items from an existing array. The size of the new array can be less than or greater than the existing array.

After copying the items from the old array, the new array is truncated or padded with nulls to obtain the required length.

int array[] = {0, 1, 2, 3, 4, 5};

int[] smallCopy = Arrays.copyOf(array, 3);  //[0, 1, 2]
int[] largeCopy = Arrays.copyOf(array, 10); //[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

Similarly, the copyOfRange() method can be used to copy the items range of the old array into a new array.

int array[] = {0, 1, 2, 3, 4, 5};

int[] smallCopyRange = Arrays.copyOfRange(array, 1, 3); // [1, 2]
int[] largeCopyRange = Arrays.copyOfRange(array, 2, 10); // [2, 3, 4, 5, 0, 0, 0, 0]

7. Conclusion

In this short Java tutorial, we learned the different ways to declare and initialize an array in Java. Explore other topics in the guide to arrays in Java.

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode