How to init an Array in Java made simple

In this comprehensive guide, we uncover the diverse techniques to init an array in Java, discussing basic and advanced approaches. Whether you’re diving into static or dynamic array creation, Arrays.copy or exploring data Streaming , this article equips you with the essential know-how to streamline your Java programming experience

Static Array Initialization

Static array initialization refers to the process of assigning values to an array at the time of declaration. When you statically initialize an array in Java, you provide the array elements’ values within braces {} at the point of creating the array.

For example:

String array[] = new String[] { "Pear", "Apple", "Banana" };
int[] datas = { 12, 48, 91, 17 };
char grade[] = { 'A', 'B', 'C', 'D', 'F' };

// Multidimensional Array
float[][] matrixTemp = { { 1.0F, 2.0F, 3.0F }, { 4.0F, 5.0F, 6.0F }};
int x = 1, y[] = { 1, 2, 3, 4, 5 }, k = 3;

Dynamic Array Initialization

Unlike static array initialization, where values are provided at the time of declaration, dynamic initialization involves allocating memory for the array first and then setting values to its elements in subsequent steps.

Here’s an example of dynamic array initialization:

int[] numbers = new int[5]; // Allocating memory for 5 elements

numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

When retrieving an array by its index, it is important to remember that index starts from 0:

how to init an array in java

Therefore, you can retrieve it by id as follows:

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

On the other hand, if you want to init a multidimensional array in a loop, you need to loop over the array twice. Example:

double[][] temperatures = new double[3][2];

for (int row = 0; row < temperatures.length; row++)
   for (int col = 0; col < temperatures[row].length; col++)
      temperatures[row][col] = Math.random()*100;

Finally, if you don’t need to operate on the array id, you can use the simplified for loop to iterate through the array:

int[] array = new int[]{2,3,5,7,11};

for (int a:array)
   System.out.println(a);

Initialization using Arrays.copyOf()

The java.util.Arrays.copyOf(int[] original,int newLength) method copies the specified array, eventually truncating or padding with zeros (if needed) so the copy has the specified length.

For example, here is how to init an array in Java using Arrays.copyOf:

int[] array = new int[]{2,3,5,7,11};
int[] copy =  Arrays.copyOf(array, 5);

A similar option also exists in the System packages, using the System.arraycopy static method:

int[] src  = new int[]{2,3,5,7,11};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );

The core difference is that Arrays.copyOf does not just copy elements, it also creates a new array. On the other hand, System.arrayCopy copies into an existing array.

In most cases, System.arrayCopy will be faster because it uses a direct native memory copy. Arrays.copyOf uses Java primitives to copy although the JIT compiler could do some clever special case optimization to improve the performance.

Using Arrays functions to fill an array

The method Arrays.setAll sets all elements of an array using a generator function. This is the most flexible option as it lets you use a Lambda expression to initialize an array using a generator. Example:

int[] arr = new int[10];
Arrays.setAll(arr, (index) -> 1 + index);

This can be useful, for example, to quickly initialize an Array of Objects:

Customer[] customerArray = new Customer[7];
// setting values to customerArray using setAll() method
Arrays.setAll(customerArray, i -> new Customer(i+1, "Index "+i));

A similar function is Arrays.fill which is the best choice if you don’t need to use a generator function but you just need to init the whole array with a value. Here is how to fill an array of 10 int with the value “1”:

int [] myarray = new int[10];
Arrays.fill(myarray, 1);

Pitfall: for an array of objects, Arrays.fill(objArray, sharedInstance) puts the same reference in every slot, not independent copies — mutating the object through one element mutates it for all of them. Use Arrays.setAll with a generator (as shown above) when you need a distinct object per slot.

Finally, if you want to convert a Collection of List objects into an array, you can use the .toArray() method on the Collection. Example:

List<String> list = Arrays.asList("Apple", "Pear", "Banana");
String[] array = list.toArray(new String[list.size()]);

Modern variant: since Java 11 you can simplify this to list.toArray(String[]::new), which lets the JVM size the array for you instead of pre-computing list.size() yourself.

Initialization using the Stream API

Finally, you can also use the Java 8 Stream API for making a copy of an Array into another. Let’s check with at an example:

String[] strArray = {"apple", "tree", "banana'"};
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);

Arrays.stream also does a shallow copy of objects, when using non-primitive types.

How to init an Array from a File

Finally, we will show how you can use the java.nio.file.Files Class to read a File in a List of Data. Then, we convert the List into a String array:

// Read the file lines into a List
List<String> lines = Files.lines(Paths.get(fileName));

// Convert the List to an array
String[] linesArray = lines.toArray(new String[lines.size()]);

Note: Files.lines() returns a Stream<String> backed by an open file channel and must be closed (e.g. with try-with-resources) to avoid a file-handle leak — calling .toArray() on it as shown doesn’t close the underlying stream/channel by itself. For most cases, Files.readAllLines(Paths.get(fileName)) is simpler since it returns a plain List<String> and closes the file for you.

Printing an Array

To verify the content of a Java Array you don’t need to loop over each item and execute a print statement. By using the do it much faster:

int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));

Here is the output:

how to initialize an array in java

Besides, please note that if you are using a nested array, then you have to use the Arrays.deepToString method instead:

System.out.println(Arrays.deepToString(deepArray));

Common errors and FAQ

  • NegativeArraySizeException: thrown at runtime if you compute an array size dynamically and it turns out negative (e.g. from an unchecked subtraction) — always validate a computed size before new T[size].
  • ArrayIndexOutOfBoundsException off-by-one: remember array length is one past the last valid index — the classic bug is looping with i <= array.length instead of i < array.length.
  • Modifying the array returned by Arrays.asList(): that list is a fixed-size view backed by the original array — you can set elements, but calling add()/remove() on it throws UnsupportedOperationException.
  • Is Arrays.copyOf() a deep copy for object arrays? No — like most of the methods here (Arrays.stream().toArray(), System.arraycopy), it’s a shallow copy: the new array holds the same object references, not independent clones.

Conclusion

In this comprehensive guide, we’ve explored the diverse array initialization techniques available in Java, equipping both novice and seasoned programmers with versatile methods to streamline their code creation.


Recommended Articles

Efficient Array Sorting in Java: A Comprehensive Benchmark Analysis

Discover the fastest sorting method for large arrays in Java. Learn about Arrays.sort(), parallelSort(), Comparator, and Collections.sort(). #Java #SortingAlgorithms #CloudNative

Efficiently Convert Arrays of Java Objects or Records into Lists with Advanced Techniques

Discover how to convert arrays of Java objects or records into lists using advanced techniques and practical examples. #Java #ListConversion #Middleware

Two Simple Ways to Read File into String in Java - A Comprehensive Guide

Learn two effective ways to read files into strings in Java, including differences and best practices.

10 Essential Java Hacks and One-Liners for Everyday Programming

Master essential Java hacks and one-liners for everyday programming, from list operations to array checks.