To declare an array, specify the data type followed by square brackets [] and the array name. This only declares the reference variable. The array memory is allocated when you use the new keyword or assign values.
Complete working Java example that demonstrates declaring, initializing, and accessing arrays
JavapublicclassGFG{publicstaticvoidmain(String[]args){// 1. Declare and initialize an array of integersint[]numbers={10,20,30,40,50};// 2. Access and print each element using a loopSystem.out.println("Array elements are:");for(inti=0;i<numbers.length;i++){System.out.println(numbers[i]);}// 3. Access a single element directlySystem.out.println("First element is: "+numbers[0]);}}OutputArray elements are:1020304050First element is: 10
Declaring an Array
Before using an array, you must declare it by specifying the data type and the array name.
Syntax:
dataType[] arrayName;
dataType arrayName[];
Examples:
// Declares an integer array
int[] numbers;
// Declares a string array
String[] names;
// Declares a double array
double[] scores;
Initialize an Array in Java
After declaration, arrays must be initialized with values. There are several ways to do this:
1. Static Initialization
Values are assigned to the array at the time of declaration.
int[] numbers = {10, 20, 30, 40, 50};
String[] fruits = {"Apple", "Banana", "Mango"};
2. Dynamic Initialization
The array is created first with a specific size, and values are assigned later.
int[] numbers = new int[5]; // Array of size 5
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
3. Initializing Using Loops
Ideal for larger arrays or sequential values:
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1; // Fills array with 1, 2, 3, 4, 5
}
4. Initialization Using Streams
Java 8 introduced IntStream to initialize integer arrays efficiently.
1. UsingIntStream.range(start, end): generates values from start (inclusive) to end (exclusive).
int[] arr = java.util.stream.IntStream.range(1, 5).toArray();
// Output: 1, 2, 3, 4
2. UsingIntStream.rangeClosed(start, end): Generates values from start to end (inclusive).
int[] arr2 = java.util.stream.IntStream.rangeClosed(1, 4).toArray();
// Output: 1, 2, 3, 4
3. UsingIntStream.of(): Directly initializes an array with specified values.
int[] arr3 = java.util.stream.IntStream.of(5, 10, 15).toArray();
// Output: 5, 10, 15
Accessing Array Elements
You can access and manipulate elements using indices, starting from 0:
int[] arr = {1, 2, 3, 4};
System.out.println(arr[0]); // Output: 1
The length property returns the number of elements in the array:
System.out.println("Array length: " + arr.length); // Output: 4
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java