Arrays in Java

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

in java array is defined in following way

dataType[] a; // preferred way.


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


int[] a= new int[8];

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


How to initialize array or set values to array

we can initialize array in 2 ways

int[] a= new int[3];

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


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

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

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

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

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++)
System.out.println(+i+" Element is "+array[i]+" it is even");
System.out.println(+i+" Element is "+array[i]+" it is odd");

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


Subscribe to YouTube

Training on Selenium

Like us on facebook



Cooking with Amol