Arrays in Java

Arrays are collection of similar kind of data type or elements.

in java array is defined in following way

[java]dataType[] a; // preferred way.[/java]

or

[java]dataType a[]; // works but not preferred way.[/java]

EXAMPLE

[java]int[] a= new int[8];[/java]

here integer array a is defined with size 8. array indexing starts with zero below figure best explains this.

array

How to initialize array or set values to array

we can initialize array in 2 ways

[java]int[] a= new int[3];

a[0] = 3;
a[1] = 4;
a[2] = 5;

[/java]

or

[java]
int[] a = {1,2,3};
[/java]

to find the size of an array there is function length it returns the size of an array.

if we want to find the size of array a simply write a.length it will return the size as 3.

2 dimensional array can be defined in below way

[java]
int[][] a = { {1,2,3},{1,2,3},{1,2,3}}; [/java]

lets see an example of an array . lets write a program to find the even and odd elements of given array.

[java]

public class ArrayExample {
public static void main(String args[])
{
int[] array= {13,55,2,11,12,11,10,14,11};

System.out.println("The size of array is : "+ array.length);

for (int i=0;i<array.length;i++)
{
if(array[i]%2==0)
System.out.println(+i+" Element is "+array[i]+" it is even");
else
System.out.println(+i+" Element is "+array[i]+" it is odd");
}
}
}

[/java]

its ouput is

The size of array is : 9
0 Element is 13 it is odd
1 Element is 55 it is odd
2 Element is 2 it is even
3 Element is 11 it is odd
4 Element is 12 it is even
5 Element is 11 it is odd
6 Element is 10 it is even
7 Element is 14 it is even
8 Element is 11 it is odd