Example 1: multidimensional array

This code is an example of using a two-dimensional array in Java.

Here, a two-dimensional array named myArray is created with the new operator. The syntax int[][] myArray = new int[2][4]; declares that the myArray is an array of arrays of integers, with 2 rows and 4 columns.

The elements of the array are then initialized with values, for example myArray[0][0] = 1; initializes the first element in the first row of the array with value 1.

In the next part of the code, a nested for loop is used to iterate through the elements of the array. The outer for loop iterates through the rows of the array and the inner for loop iterates through the columns of each row. The value of each element is printed using System.out.print(myArray[i][j]);.

Finally, the inner loop prints a new line after each row is processed by the inner loop, to keep the output organized.

import java.util.Arrays;

public class MultidimensionalArrayExample {
	public static void main(String[] args) {
		int[][] myArray = new int[2][4];
 
		myArray[0][0] = 1;
		myArray[0][1] = 2;
		myArray[0][2] = 3;
		myArray[0][3] = 4;
		myArray[1][0] = 5;
		myArray[1][1] = 6;
		myArray[1][2] = 7;
		myArray[1][3] = 8;

		for (int i = 0; i < myArray.length; i++) {
			for (int j = 0; j < myArray[i].length; j++) {
				System.out.print(myArray[i][j]);
			}
			System.out.println();
		}
	}
}
Output
1234
5678