What is Array in Java How it works such as 2D or 3D array ne
What is Array in Java? How it works such as 2D or 3D array, need several examples of code. Thanks!
Solution
Array is a collection of homogenous(similar type) elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
syntex for array declaratrion:
arrayRefVar=new datatype[size];
Example for one dimension array:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Syntex of two dimension array:
dataType[][] arrayRefVar;
example of 2D Array:
int[][] arr=new int[3][3]; //3 row and 3 column
Exxample of 2D Array:
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+\" \");
}
System.out.println();
}
}
}
Program for Addition of two 2D array:
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+\" \");
}
System.out.println();//new line
}
}
}
program for 3D Array:

