C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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 ArrayExample{
	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








COMMENTS