Arrays in Java

392


The Array is used to group similar type of elements.
Following is how you declare an array.

type[] identifier;
or
type identifier[];

ex.

int[] intValuesArray;

Following is the syntax to initialize an Array

identifier = new type[size];

ex.

intValuesArray = new int[10];

You can do this in one line as shown below

int[] intValuesArray = new int[10];

Inline Initialization

You can assign values to array at the time of declaration itself as shown in following code

int intValuesArray[5]={1,2,3,4,5};

Reading & Writing

Following program explains you how to write data to an array and how to read from it

class Arrays {
	public static void main(String[] args) {
		int[] intValuesArray = new int[5]; //Declaration

		// Writing to Array
		intValuesArray[0] = 1;
		intValuesArray[1] = 2;
		intValuesArray[2] = 3;
		intValuesArray[3] = 4;
		intValuesArray[4] = 5;

		// Reading from Array

		int x = intValuesArray[1];
		System.out.println("Value at 2nd position is: " + x);

	}
}

Output:

Value at 2nd position is:2

Multi dimensional Arrays

Multi dimensional Arrays are Arrays of Arrays, these can be of any dimensions.
Following example shows you creating a two dimensional array and writing, reading data from and to the array.

public class TwoDimentionalArray {
	public static void main(String[] args) {
		
		int twoDimentionalArray[][] =  new int[2][2]; //Declaration
		
		// Writing to Two Dimensional Array
		twoDimentionalArray[0][0] = 11;
		twoDimentionalArray[0][1] = 12;
		
		twoDimentionalArray[1][0] = 21;
		twoDimentionalArray[1][1] = 22;
		
		// Reading to Two Dimensional Array
		
		System.out.println("Value at [0][0] position is: " + twoDimentionalArray[0][0]);
		System.out.println("Value at [0][1] position is: " + twoDimentionalArray[0][1]);
		System.out.println("Value at [1][0] position is: " + twoDimentionalArray[1][0]);
		System.out.println("Value at [1][1] position is: " + twoDimentionalArray[1][1]);
	
	}
}

Output:

Value at [0][0] position is: 11
Value at [0][1] position is: 12
Value at [1][0] position is: 21
Value at [1][1] position is: 22