Arrays In Java


Array is group of elements of similar type represented by a common variable.

ie An array can contain a single type of data type only.


eg

int length=new int[20];

or int[] length=new int[20];

the above statement creates an array of integer values with max array length of 20.


We can now declare values of the array element, like if we want to put first value of array with value of 35

Syntax will be :

length [0]=35;

this command places the value at first element(index position = 0 ) as 35.

Since it is an integer array, we cannot put any other data type in this particular array or the compiler will show an error message.

 

To read a particular element in array we have to simply call by the index value at which it is present.

eg if the above array has an value of 56 at index of 6 and we wish to copy that value in another fixed variable

int value = length[6];

the above command places value of 56 in variable value.

 

2D arrays

2d arrays are collection of elements of single data type in double dimension.

Declaration

int array[][]=new int[10][10];

in above statement we created a 2D array with 10 rows and 10 columns.


coding example:



myClass.java:

package array_demo;

public class myclass {

	public static void main(String[] args) {
		int array[][]= new int[5][5];
		int i, j, k = 10;
		
		for(i=0; i<5; i++) {
			for(j=0; j<5; j++) {
				array[i][j] = k++;
		}
		
		}
		for(i=0; i<5; i++) {
		for(j=0; j<5; j++)
		System.out.print(array[i][j] + " ");
		System.out.println();

	}

}
}

output:
10 11 12 13 14 
15 16 17 18 19 
20 21 22 23 24 
25 26 27 28 29 
30 31 32 33 34 



Related Tutorials