Array in Java

An array is a collection of similar types of elements that have continuous memory locations. Java array is like an object that contains elements only of a similar data type.

The length of an array should be specified at the time of creation. After declaration, the array length is fixed and cannot be changed later.

The array is index-based, index number starts from 0, the first element of the array is stored at index 0. Each item in an array is called an element, and each element is accessed by its numerical index.

Array in Java, Types of Array in java, Array in Java Program


If we want to represent a set of five numbers, in java with the help of array we can do this like this –
int rollNos = new int[5];

and then the values in each index can be assigned as follows –

number [ 0 ] = 2; // index 0
number [ 1 ] = 4; // index 1
number [ 2 ] = 6; // index 2
number [ 3 ] = 8; // index 3
number [ 4 ] = 10; // index 4

Types of Array in java

1. Single Dimensional Array

2. Multidimensional Array

Single Dimensional Array in Java

Syntax

dataType[] arr; (or)  
dataType []arr; (or)  
dataType arr[];  

class Demo
{
	public static void main(String args[])
	{    
	int[] a=new int[3];//declaration   
	a[0]=10;//initialization  
	a[1]=20;  
	a[2]=30;  
	//printing array  
	System.out.println("Single dimensional array elements are");    
	System.out.println(a[0]);    
	System.out.println(a[1]);    
	System.out.println(a[2]);    
	}
}
Example Output

Multidimensional Array in Java

Syntax

dataType[][] arrayRefVar; (or)  
dataType [][]arrayRefVar; (or)  
dataType arrayRefVar[][]; (or)  
dataType []arrayRefVar[];

class Demo{  
public static void main(String args[]){  

int arr[][]={{100,200,300},{2000,4000,5000},{40000,40000,50000}};  
 
for(int d=0;d<3;d++){  
 for(int a=0;a<3;a++){  
   System.out.print(arr[d][a]+" ");  
 }  
 System.out.println();  
}  
}}
Example Output

Share