2D Array in Java
In this instructional exercise, you will find out about 2D cluster in Java. In the event that
you don’t think about what is exhibit then I would prescribe you to peruse the
past instructional exercise: Array in Java (1D)
2D Array in Java
The exhibit is an assortment of comparable sort of components. The exhibit can
be of any measurement yet, for the most part, we don’t go past 3 measurements. 2D exhibit in
java is a cluster with two measurements, lines and sections. The 2D exhibit is additionally known as a network.
Pronounce 2D Array in Java
A 2-dimensional cluster can be announced in Java in the following
two different ways.
Syntax
data_type [][]array_name;
data_type array_name[][];
Example:
int [][]arr;
int arr[][];
In the above model, I have pronounced reference variable that
will contain the reference of a 2D exhibit article.
Make 2D Array in Java
In Java, the 2D cluster is made utilizing new watchword in following way.
Syntax
array_name=new data_type[row][column];
Example:
arr=new int[3][3];
Sentence structure
In the above model, I have made a 2D cluster with 3 lines and 3
segments. This exhibit can store 9 (3×3) components.
Proclaim, Create and Initialize 2D Array in Java
The 2D exhibit can be proclaimed, made and instated at the same time.
For this situation, we don’t have to compose the new watchword. Take beneath model.
int arr[][]={{1,2},{3,4},{5,6}};
This will make a 2D exhibit and instate it. The abovementioned
cluster has 3 lines and 2 segments. To get to the components of the 2D exhibit we need to
utilize two lists, one for lines and another for segments.
Program Example for 2D Array in Java
Lets make a basic program to make a 2D cluster, stores a few
values in it and afterwards print the qualities.
class Array2D
{
public static void main(String...s)
{
int arr[][]={{10,20},{30,40},{50,60}};
for(int i=0;i<3;++i)
{
for(int j=0;j<2;++j)
System.out.print(arr[i][j]+" ");
System.out.print("n");
}
}
}
In this program I have utilized two for circles, the external circle is
for lines and the internal circle is for segments. I have introduced the cluster while
making it. We can take the qualities from the client too. We should make another program
that will peruse the qualities in the cluster from the client and afterwards print it.
import java.util.Scanner;
class Array2D
{
public static void main(String...s)
{
int arr[][]=new int[3][3];
int i=0,j=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter array elements row wise");
for(i=0;i<3;++i)
for(j=0;j<3;++j)
arr[i][j]=sc.nextInt();
System.out.println("");
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
System.out.print(arr[i][j]+" ");
System.out.print("n");
}
}
}
Output:
In the above program, I have utilized Scanner class to peruse the qualities
from the console. nextInt() strategy is utilized to peruse whole number qualities.
In the event that you have any questions identified with the above instructional exercise, at that point feel allowed to ask by remarking beneath.