Two Dimensional Array Java Program

Sharing is healthy !!

Two dimensional array java program are just array of an array.

Let’s discuss about the two dimensional arrays in java. For example,

Two Dimensional Array Java Program

I have this table that has six rows and two columns. The first column represents the EmpID (Employee ID) and the second column represents the EmpName (Employee Name).

We will write a program that initializes EmpID, EmpName and then prints it out,

Example: Two Dimensional Array Java program

Also Read – Array Copy Program in Java

public class TwoDimensionalArray
{
public static void main(String[] args)
{
String twoDimensional [][] =
{
{"1501201","Chris"},
{"1501202","Sam"},
{"1501203","Smith"},
{"1501204","Williams"},
{"1501205","Joe"},
{"1501206","Mark"}
};
for(int a = 0;a < twoDimensional.length;a++)
{
System.out.println(twoDimensional[a][0] + "\t" + twoDimensional[a][1]);
}
}
}

Output:

Two Dimensional Array Java Program

Above example is a two dimensional araray class. It has a main method. We are declaring the two dimensional array. As we know each dimension needs to be square brackets. We put two brackets to declare that it’s two dimensional and the name of the array is twoDimensional.

And we are separating each row by the comma. So that tells it’s the next row. Once the EmpID and EmpName gets initialized what we are going to do is we are going to have a loop that goes through each of the ids, names and then print. After running the program the output is as above.


using scanner class

import java.util.Scanner;

public class TwoDimensionalDemo
{
public static void main(String[] args)
{
int a, b, row, column;
int arrEven[][] = new int[10][10];
Scanner sc = new Scanner(System.in);                   

System.out.print("Please enter number of rows (Max. limit 10) :  ");
row = sc.nextInt();
System.out.print("Please enter number of columns (Max. limit 10) : ");
column = sc.nextInt();

System.out.print("Please enter " + (row * column) + " array elements : ");
for(a = 0; a < row; a++)
{
for(b = 0; b < column; b++)
{
arrEven[a][b] = sc.nextInt();
}
}

System.out.print("The two dimensional array is : \n");     for(a = 0; a < row; a++)
{
for(b = 0; b < column; b++)
{
System.out.print(arrEven[a][b]+ "  ");
}
System.out.println();
}
sc.close();
}
}

Output:

Please enter number of rows (Max. limit 10) :  3
Please enter number of columns (Max. limit 10) : 3
Please enter 9 array elements :
2 4 6 8 10 12 14 16 18
The two dimensional array is :
2 4 6
8 10 12
14 16 18


conclusion

So this is all about two dimensional array java program using scanner class and without scanner class.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like.

Sharing is healthy !!

Leave a Reply

Your email address will not be published.