How to Initialize an Array in Java?
Overview
An array is a data structure used to store values of the same type. The values stored in arrays are referred to as elements and each element of the array is at a specific index. To initialize an array simply means to assign a value to the array.
Syntax to initialize array in Java:
Introduction to Initializing Array in Java
To use an array and store values in them, we have to initialize the array. The array initialization in java can be done in more than one way which is explained below:
Initializing an Array Without Assigning Values
how to initialize an array without assigning values, for this we pass the size to the square braces([]). Doing this, java will assign the default value 0 to each element of the array in the case of an int array.
Similarly, in the case of a boolean array, it will be false, in the case of a String array the default value is null in java, and in the case of a char array, the default value is Unicode (\u0000).
Example: Default value in an integer array
The output of this code is: The program declares an array of integers called num with a length of 5 using the new keyword. Since no values are passed during initialization, all elements of the array are set to their default value of .
Example: Default value in String array
The output of this code is:
Initializing After the Declaration of the Array
The second way, how to initialize array in java is after the array declaration. In this method, we first declare the array and then initialize the array.
Syntax of array declaration: datatype[] arrayName;
Syntax for how to initialize array in java after declaration: arrayName = new datatype[]{value1,value2,.....,valuen};
Example:
The output of this code is:
Initialize and Assign Values Together
The third way of how to initialize array in java is to declare and initialize the array together.
Syntax: dataType [] arrayName= {value1,value2,.....,valuen};
Example:
The output of this code is:
How to Initialize String Array in Java ?
We can assign string array in the java same as we did in the above examples, below is the example to initialize and assign values to string array together.
Example:
The output of this code is:
Conclusion
- An array is a data structure used to store values of the same type in Java.
- To use an array and store values in it, we have to initialize the array.
- Array initialization in Java can be done in more than one way.
- The first way is to initialize an array without assigning values, and Java assigns default values to each element of the array.
- The second way is to initialize an array after the array declaration, and we first declare the array and then initialize it.
- The third way is to declare and initialize the array together.