Arrays are used to store multiple values in a single variable instead of declaring separate variables for each value.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.
Syntax :
String[] fruits;
OR
String fruits[];
You can insert value in array as below,
String[] fruits = {"Apple","Orange", "Banana", "Grapes"};
Types of Array in java
There are two types of array.
- Single Dimensional Array
- Multidimensional Array
Single Dimensional Array can be inistantiated,defined and declared as below.
arrayVar=new datatype[size];
Example ,
int i[]=new int[3];//declaration and instantiation
i[0]=30;//initialization
i[1]=40;
i[2]=50;
Multidimensional Array can be defined and declared as below.
dataType[][] arrayVar;
OR
dataType [][]arrayVar;
OR
dataType arrayVar[][];
OR
dataType []arrayVar[];
Multidimensional Array can be inistantiated as below.
dataType[][] arrayVar = new dataType[][];
Example,
int[][] arrayVar=new int[2][2];//2 row and 2 column
arrayVar[0][0] =1;
arrayVar[0][1] =2;
arrayVar[1][0] =3;
arrayVar[1][1] =4;
Comments