int[][] numbers = {
{10, 20, 30},
{40, 50, 60}
};
int
, float
, String
, etc.).
dataType[][] arrayName;
int[][] numbers;
dataType arrayName[][];
dataType [][]arrayName;
int numbers[][];
int [][]numers;
new
keyword in Java.
arrayName = new dataType[rows][columns];
numbers = new int[2][3];
dataType[][] arrayName = new dataType[rows][columns];
int[][] numbers = new int[2][3];
0
for int
, 0.0
for float
, null
for objects).
arrayName[rowIndex][columnIndex] = value;
int[][] numbers = new int[2][3];
numbers[0][0] = 10;
numbers[0][1] = 20;
numbers[0][2] = 30;
numbers[1][0] = 40;
numbers[1][1] = 50;
numbers[1][2] = 60;
dataType[][] arrayName = {
{value1, value2, value3, ...},
{value4, value5, value6, ...},
...
};
int[][] numbers = {
{10, 20, 30},
{40, 50, 60}
};
int[][] numbers = new int[][] {
{10, 20, 30},
{40, 50, 60}
};
[0][0]
and the last element is at index [rows-1][columns-1]
.
int[][] numbers = {
{10, 20, 30},
{40, 50, 60}
};
System.out.println(numbers[0][1]); // Output: 20
System.out.println(numbers[1][2]); // Output: 60
for(int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers[i].length; j++)
{
System.out.println(numbers[i][j]);
}
}
for(int[] row : numbers)
{
for(int num : row)
{
System.out.println(num);
}
}
public class MainApp1
{
public static void main(String[] args)
{
// 1. Declare and create a 2D array of size 2x3
int[][] numbers = new int[2][3];
// 2. Initialize array elements
numbers[0][0] = 10;
numbers[0][1] = 20;
numbers[0][2] = 30;
numbers[1][0] = 40;
numbers[1][1] = 50;
numbers[1][2] = 60;
// 3. Access and print array elements using nested for loop (Way 1)
System.out.println("Way 1:");
for (int i = 0; i < numbers.length; i++)
{
for (int j = 0; j < numbers[i].length; j++)
{
System.out.print(numbers[i][j] + " ");
}
System.out.println(); // Move to next row
}
// 4. Access and print array elements using nested for-each loop (Way 2)
System.out.println("Way 2:");
for (int[] row : numbers)
{
for (int num : row)
{
System.out.print(num + " ");
}
System.out.println(); // Move to next row
}
}
}
Way 1: 10 20 30 40 50 60 Way 2: 10 20 30 40 50 60
public class MainApp2
{
public static void main(String[] args)
{
// 1. Declare, create, and initialize a 2D array in a single line
int[][] numbers = {
{10, 20, 30},
{40, 50, 60}
};
// 2. Access and print array elements using nested for-each loop
System.out.println("Numbers are:");
for (int[] row : numbers)
{
for (int num : row)
{
System.out.print(num + " ");
}
System.out.println(); // Move to next row
}
}
}
Numbers are: 10 20 30 40 50 60
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.