Arrays in Java

Arrays are used to store a set of similar data's of same data type.

Imagine if want to store five roll numbers in a Java program. What you will do ?

You will declare variables for every roll numbers separately like rollno1, rollno2. Right ?

Suppose imagine if you need 500 roll numbers to be stored.

We should write many lines of code or statements. To avoid this, we can use arrays.


To declare a array

datatype array_name[]=new datatype[array_size];


To initialize a array

array_name[index]=value;


We can also combine declaration and initialization as above,

datatype array_name={value1,value2};


Example

public class Arrays {

public static void main(String args[]) {

int rollno[]=new int[2];

rollno[0]=1;

rollno[1]=2;

}

}

Try In Compiler

Arrays can be 1D, 2D, 3D based on the application requirements.

The above is 1D array, For 2D arrays we can use datatype variable_name[][]=new variable_name[][];. Similarly for 3D, 4D we an use additional square boxes.

Index of a array variable starts from 0 to size-1 i.e rollno[0] to rollno[size-1] in above example.

We can use any datatype whenever needed.