Declaring and initializing an array is quite a typical task for any programmer in Java. Since Java arrays are one of the basic data structures, programmers should know every detail about its initialization and declaration. Java provides some standard methods to initialize and declare arrays in Java.
This article will cover all these methods with ins and outs explanations of the code examples.
Java Arrays
Arrays are those data structures that allow users to store multiple elements in a single variable. It collects data elements of the same type, i.e., homogeneous data structures.
So, in simple terms, users can declare an array and initialize multiple elements of the same data type. They do not need to declare a variable for each element.
Array declaration informs the compiler about the presence of an entity in the program and specifies the location. Initialization lets users assign a value/element to an array variable. So, with the declaration, users should also initialize the array variable with values.
There are some commonly applied techniques in Java for initializing or instantiating an array as users declare it, and these are:
- Array Declaration in Java
- Array Initialization in Java
- IntStream.range()
- IntStream.of()
- IntStream.rangeClosed()
- Java Array Loop Initialization
Array Declaration in Java
Declaration of an array is the same as declaring a variable in Java. First, users must specify the data type of the array elements. Then, users set the array name with [] (square brackets) to denote it as an array.
The syntax to declare an array is as follows:
datatype array_Name[];
datatype [] array_Name;
Most expert programmers often prefer the second technique, clearly specifying which data type the array_Name is.
Array Initialization in Java
For the initialization process, users should use the Java "new" keyword followed by the data type of the array with [] (square brackets). The following syntax illustrates how to initialize an array with elements and specify the size:
datatype [] array_Name = new datatype [ size ]
Here, the size specifies how many elements the array can store and is immutable.
For instance:
int[] array_name= new int[20];
array_name[2] = 9;
Here, the array_name is a variable that specifies an array of size 20. But we have initialized an element, i.e., 9, using the index number 2.
But users can also specify the size of the array by declaring and initializing elements to the array using curly brackets.
For instance:
int array_name[] = {1, 5, 10, 15};
Here, the size of the array is 4 with integer-type elements. Thus, the size of the Java array is the number of elements we have specified inside the curly brackets.
If users want to initialize an array with string-type elements, then simply:
int[] another_array= {"A", "B", "C", "D", "E"};
Also, using the "new" keyword, users can initialize an array.
int[] first_array = new int[]{5, 8, 10};
String[] second_array = new String[]{"A", "B", "C", "D", "E"};
Using the Java IntStream.range() with toArray() methods
The IntStream is a Java class, which represents integer primitive and is a specialization of the String interface. IntStream is a component of the java.util.stream package. Users use this to implement AutoCloseable and BaseStream interfaces. It is a Java interface for initializing and declaring an array.
The IntStream interface provides the range() method that returns a sequential ordered IntStream. It starts from startInclusive (inclusive) to endExclusive (exclusive), incrementing by one.
Syntax:
int[] intArray = IntStream.range(int startInclusive, int endExclusive).toArray();
Code Snippet:
import java.util.*;
import java.util.stream.IntStream;
public class Array {
public static void main(String[] args) {
IntStream stream = IntStream.range(0, 10);
int[] demo = stream.toArray();
System.out.println(Arrays.toString(demo));
}
}
Output:
Explanation:
Executing the above program returns an array with numbers 0 to 9. Here, we passed the beginning and end of the array as parameters. The toArray() method then converts it into an array. The range that we have specified, i.e., (0, 10), denotes the size of the array, i.e., 10.
Using the Java IntStream.of() and toArray() methods
Here, using this IntStream.of() method, users can declare a Java array with some pre-defined values such as:
int[] demo = IntStream.of(5, 8, 20, 2, 12, 7).toArray();
The IntStream.of() method also returns a sequential stream of elements in an array. Let us see an example of the IntStream.of() method:
Code Snippet:
import java.util.*;
import java.util.stream.IntStream;
public class Array {
public static void main(String[] args) {
IntStream stream = IntStream.of(8, 41, 23, 16, 2, 10, 19, 50, 36, 7);
int[] demo = stream.toArray();
System.out.println(Arrays.toString(demo));
}
}
Output:
Explanation:
The above code produces an array with all the given unsorted elements. But users can also sort the elements in ascending or descending order with the sorted() method.
import java.util.*;
import java.util.stream.IntStream;
public class Array {
public static void main(String[] args) {
IntStream stream = IntStream.of(8, 41, 23, 16, 2, 10, 19, 50, 36, 7);
int[] demo = stream.sorted().toArray();
System.out.println(Arrays.toString(demo));
}
}
Output:
Using the IntStream.rangeClosed() with toArray() method
import java.util.*;
import java.util.stream.IntStream;
public class Array {
public static void main(String[] args) {
IntStream stream = IntStream.rangeClosed(1, 20);
int[] demo = stream.sorted().toArray();
System.out.println(Arrays.toString(demo));
}
}
Output:
Explanation:
The IntStream.rangeClosed() method works similarly to the IntStream.range() method. But if users want to include the last element in the range, they can use the IntStream.rangeClosed() method. Here, we passed range (1, 20), so the method returned an array with numbers from 1 to 20.
Initialization using Java Loop
Initializing without Values
Let us declare and initialize an array without assigning values using the for loop and square brackets.
Code Snippet:
public class Array {
public static void main( String args[] ) {
int[] demo = new int[10];
for (int i = 0; i < 10; i++)
{
System.out.println(demo[i]);
}
}
}
Output:
Explanation:
A Java array returns 0 as the default. In the above example, we used square brackets with the "new" keyword to initialize an array. Then, the for loop will iterate over the specified elements of given size of the array, i.e., 10.
Initializing Array after Declaration
public class Array {
public static void main( String args[] ) {
int [] demo;
demo = new int[]{10, 20, 40, 50, 60, 70, 80};
for (int i = 0; i < 5; i++)
{
System.out.println(demo[i]);
}
}
}
Output:
Explanation:
Here, we initialized an array with integer values. The number of elements in the array specifies the array size, and the for loop helps iterate over each value sequentially.
Conclusion
This article caters to all the techniques of initializing and declaring arrays in Java. IntStream.of(), toArray(), IntStream.rangeClosed(), IntStream.range() methods help users to initialize elements into the declared array.
Users can add values into the Java array using the for loops, {} curly brackets, and the new keyword. Users find multiple options to initialize and declare arrays in different scenarios.