Home »
Java programming language
How to declare and initialize an array in Java?
Learn: How to declare and initialise array elements in Java programming, Here, you will find different 3 ways to declare and initialize arrays.
There are many ways to declare and initialize array elements in java programming, but here we are taking three different ways to do so. Here, we are writing three different ways:
Consider the given statement (s) (type 1):
int[] arr1 = {10,20,30,40,50};
Consider the given statement (s) (type 2):
int[] arr2;
arr2 = new int[] {100,200,300,400,500};
Consider the given statement (s) (type 3):
int arr3[] = {11,22,33,44,55};
Array declaration and initialization example in java
This program is declaring three one dimensional integer arrays and initialising the array elements by different 3 methods.
public class Main {
public static void main(String args[]) {
//type 1
int[] arr1 = {10, 20, 30, 40, 50};
//type 2
int[] arr2;
arr2 = new int[] {100, 200, 300, 400, 500};
//type 3
int arr3[] = {11, 22, 33, 44, 55};
//print elements
System.out.println("Array elements of arr1: ");
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + "\t");
}
//printing a line
System.out.println();
System.out.println("Array elements of arr2: ");
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + "\t");
}
//printing a line
System.out.println();
System.out.println("Array elements of arr3: ");
for (int i = 0; i < arr3.length; i++) {
System.out.print(arr3[i] + "\t");
}
//printing a line
System.out.println();
}
}
Output
Array elements of arr1:
10 20 30 40 50
Array elements of arr2:
100 200 300 400 500
Array elements of arr3:
11 22 33 44 55
Creating an integer array, assign, and print the values
// Java program to create an integer array,
// assign, and print the values
class Main {
public static void main(String[] args) {
// declare an integer array
int[] intArr;
// allocate memory for 5 integers
intArr = new int[5];
// initialize the first element
intArr[0] = 10;
// initialize the second element
intArr[1] = 20;
// And, so on...
intArr[2] = 30;
intArr[3] = 40;
intArr[4] = 50;
// accessing all elements
for (int i = 0; i < intArr.length; i++)
System.out.println("Element at index " + i +
" : " + intArr[i]);
}
}
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50