An array in Java is a data structure that is used to store multiple values of the same data type in a single variable name. To access the element of an array, we use the index of the element, by default the indexing of the elements starts from 0. In this blog, we will learn how to declare and initialize an array in Java using different approaches.
Table of Contents:
Declare an Array in Java
To declare an array in Java, we must follow the basic syntax of it:
Syntax to Declare an Array
type [] arr;
C-Style Syntax to Declare an Array
type arr [];
In this example syntax:
- type is the data type of the array(like: int, String, etc.)
- arr is the name of the array.
Declaring and Initializing an Array Together
We can declare and initialize an array in a single line.
int[] numbers = new int[5];
Here, we have declared an array of length 5 and by default Zero(0) is initialized to each element of the array.
Initialize an Array in Java
To initialize an array in Java, we have different approaches, let’s discuss them in more detail:
1. Initialize an Array with a Fixed Size and Default Values
To initialize an array with a fixed size and some default values, we have to follow the below given approach:
By default, the value of array numbers is 0, array flags is false, and array str is null.
2. Initialize an Array with Specific Values
If you want to assign some specific values to the array, we can also do this with the help of the following syntax:
3. Initialize an Array Using Curly Braces { }
We can initialize an array using curly braces and assign all the elements separated by a comma.
Here, we have initialized a string array using curly braces and assigned some values that are separated by commas.
4. Initialize an Array with Non-Default Values
We can assign some values to the array as well during initialization.
5. Initializing an Array Using Loops
We can initialize an array using loops to dynamically change the elements.
Here, we have initialized an array and assigned values to the array that are 10 times the index.
6. How to Initialize an Array with the new Keyword
We can use the new keyword to allocate memory for an array without immediately assigning specific values to its elements. It assigns values based on the data type (0 for int, false for boolean, null for objects).
Here, for a char array, the by default value is a null character.
7. Initializing an Array Using Arrays.fill()
We can use Arrays.fill() to initialize an array with a specific value:
The above code will initialize an array of length 5, and assign 42 to each element of the array.
8. Initializing an Array Using Arrays.setAll()
We can initialize an array using Arrays.setAll() to initialize the values into a functional style. This method takes a lambda expression or function to generate values dynamically based on the index.
The above code will initialize an array of length 5, and assign the value to the double of their index.
Initialize a Two-Dimensional (2D) Array in Java
A 2D array (two-dimensional array) is a data structure that stores data in the form of rows and columns. It is used to represent data in a grid format. We can also initialize a 2D array in Java.
Initialize a Multidimensional Array in Java
In Java, a multidimensional array is essentially an array of arrays. Here are the different ways to initialize a multidimensional array:
Direct Initialization (Static Initialization)
You can directly Intilialize a 3D array (cube) directly with specific values. In this code, the array has 2 layers, each containing 2 rows and 2 columns. The values are assigned statically during declaration.
Using new Keyword (Dynamic Initialization)
You can dynamically initialize a 3D array (matrix) using the new keyword. In the code below the array has generally the 3 layers, each with 4 rows and 5 columns. All the elements are initialized to their default values (0 for int).
Jagged Array Initialization in Java
A jagged array in Java is generally a multidimensional array where each of the rows can have different rows and columns. Unlike a standard 2D array, jagged arrays allow variable-length rows.
Declaring a Jagged Array
int[][] jaggedArray = new int[3][];
Here, only the number of rows (3) is specified, and columns are assigned later.
Initializing a Jagged Array
1. Using new Keyword
The code mentioned below shows how to initialize the columns of the jagged array dynamically. Each row can have a different number of columns:
- Row 0 has 2 columns.
- Row 1 has 4 columns.
- Row 2 has 3 columns.
2. Direct Initialization with Values
The code mentioned below demonstrates to directly initialize a jagged array with specific values. Each row has a different number of columns:
- Row 0: 2 columns ({1, 2}).
- Row 1: 4 columns ({3, 4, 5, 6}).
- Row 2: 3 columns ({7, 8, 9}).
Advanced Initialization Using Streams
In Java, you can use Streams from the java.util.stream package to initialize an array. Let’s learn this concept in more detail:
1. Using IntStream.range()
We can create and initialize an array dynamically using IntStream.range(). That prints the data within a specified range.
The above code will create an array with values 0 to 9.
2. Using IntStream.rangeClosed()
We can use IntStream.rangeClosed(start, end) method to initialize the array, which includes both start and end values, unlike IntStream.range() which excludes the end value.
The above code will initialize an array with values 1 to 10 (inclusive).
3. Using IntStream.of()
We can use IntStream.of() method to create an array of specified values.
Let’s utilize all the above concepts of Streams with an example code:
Output:
How to Create Dynamic Arrays in Java
To create dynamic arrays in Java, we have to use ArrayList. Dynamic array means we can grow and shrink the size of the arrays according to our needs.
Example:
Output:
How to Create Immutable Arrays Using List.of() and toArray()
Immutable arrays are arrays whose elements cannot be modified after creation. To create immutable arrays we have to use List.of() and toArray() in Java.
Example:
Output:
Conclusion
So far in this blog, we have learned how we can declare and initialize an array in Java. Java provides multiple ways to declare and initialize arrays, from simple fixed-size arrays to advanced functional-style initialization. If you want to be an expert in Java language, you may refer to our Java Course.