An array in Java is a linear data structure that is used to store multiple values of the same data type. In an array, each element has a unique index value, which makes it easy to access individual elements. We first need to declare the size of an array because the size of the array is fixed in Java. In an array, we can store elements of different data types like integer, string, character, etc.
In this article, we will discuss different ways to declare and initialize an array in Java.
1. Basic Array Declaration and Initialization Declare an Array in JavaUnderstanding how to declare an array in Java is very important. In Java, an array is declared by specifying its data type, an identifier, and adding brackets []
to indicate it is an array.
type arrayName [];
type [] arrayName;
int
, String
).Here, the size of the array is not mentioned because a reference to an array is created in memory. It can also be known as the memory address of an array.
Initialize an Array in JavaAfter declaring an array, we have to initialize it with values, as we have to do with other variables. In an array, we have to assign multiple values, so the initializing process is not as simple as with variables. We will cover the different ways to initialize arrays below.
1. Initialize an Array with a Fixed Size and Default ValuesIn Java, an array can be initialized with default values when the size of the array is declared with square brackets [ ].
int [] arr = new int[20]; // Array of size 20, initialized with default values (0)
We can specify the size of an array at the time of initialization. When we created this way, each element gets a default value (0 for integers, false
for boolean, and null
for objects).
When we know the values and we want to store it, we can initialize the array with specific values directly.
3. Initialize an Array Using Curly Bracesint[] arr = {1, 2, 3, 4, 5}; // Array initialized with specified values
{ }
An array can also be initialized by using curly braces where we don't have to declare the size of the array. All the non-default values are initialized in the curly braces which are separated by a comma.
String[] arr = {"Geeks", "of", "Geeks"};
In the above example, a string-type array is initialized with non-default values using curly braces.
In Java, we can also initialize an array with particular values. For that, we need to initialize each value one by one. But this method is only useful for small sizes of arrays not for arrays having large sizes. For large-size arrays, we have to use a loop to initialize non-default values.
int[] arr = new int[4];
arr[0] = 2;
arr[1] = 4;
arr[2] = 6;
arr[3] = 8;
In the above example, an integer type array of size 4 is declared and then 4 non-default values are initialized in it.
5. Initializing an Array Using LoopsWe can also use loops to initialize array elements with specific values. This method is specially useful for larger arrays.
Example:
Using Arrays with Unknown Sizeint[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1; // Fills array with values 1, 2, 3, 4, 5
}
If the size of the array is unknown but we want to fill it dynamically, we can initialize it first with a fixed size and add values later or use a data structure like ArrayList
. Some common operations are mentioned below:
We can access and manipulate array elements by referring to their index.
Using Array Lengthint[] arr = {1, 2, 3, 4};
System.out.println(arr[0]); // Output: 1
We can use the length property to return the number of elements in an array.
2. Advanced Initialization Using Streamsint[] arr = {1, 2, 3, 4};
System.out.println("Array length: " + arr.length); // Output: 4
An array can be initialized by using a stream interface. The IntStream interface in Java offers additional ways to initialize arrays with sequential or predefined values. Below are three instream interfaces that are used to initialize an integer type array.
1. Using IntStream.range()It is used to initialize an array of integers within a given range.
Example:
2. Using IntStream.rangeClosed()int[] arr1 = java.util.stream.IntStream.range(1, 5).toArray();
// Output: 1 2 3 4
It creates an array within a range (inclusive of the end).
Example:
3. Using IntStream.of()int[] arr2 = java.util.stream.IntStream.rangeClosed(1, 4).toArray();
// Output: 1 2 3 4
It directly initializes an array with specified values.
Example:
Implementationint[] arr3 = java.util.stream.IntStream.of(1, 2, 3, 4).toArray();
// Output: 1 2 3 4
Below is a simple program demonstrating different ways of initializing an array.
Java
// Java program to demonstrate different ways of
// initializing an integer array
import java.util.stream.IntStream;
public class Geeks {
public static void main(String[] args) {
// an array of integers using IntStream.range()
// method
int[] arr1 = IntStream.range(1, 5).toArray();
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
System.out.print('\n');
// an array of integers using
// IntStream.rangeClosed() method
int[] arr2 = IntStream.rangeClosed(1, 4).toArray();
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
System.out.print('\n');
// an array of integers using IntStream.of()
// method
int[] arr3 = IntStream.of(1, 2, 3, 4).toArray();
for (int i = 0; i < arr3.length; i++) {
System.out.print(arr3[i] + " ");
}
}
}
1 2 3 4 1 2 3 4 1 2 3 4
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4