Java 2-dimensional Array

ww‮w‬.lautturi.com
Java 2-dimensional Array

In Java, you can use a two-dimensional array to store a matrix or a table of values. A two-dimensional array is an array of arrays, where each element of the array is itself an array.

To create a two-dimensional array in Java, you can use the following syntax:

type[][] arrayName = new type[size1][size2];

Here, type is the type of the elements in the array (such as int, double, or String), arrayName is the name of the array, size1 is the size of the first dimension (the number of rows), and size2 is the size of the second dimension (the number of columns).

Here is an example of how you can create a two-dimensional array of integers in Java:

int[][] myArray = new int[3][4];

This creates a two-dimensional array called myArray with 3 rows and 4 columns.

To access an element in the array, you can use the following syntax:

arrayName[row][column]

Here, row is the index of the row (starting from 0) and column is the index of the column (starting from 0).

Here is an example of how you can access and modify elements in a two-dimensional array:

int[][] myArray = new int[3][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;
myArray[2][0] = 9;
myArray[2][1] = 10;
myArray[2][2] = 11;
myArray[2][3] = 12;

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();
}

This code creates a two-dimensional array with 3 rows and 4 columns, and assigns values to the elements of the array. It then uses a nested for loop to iterate over the elements of the array and print them to the console. The output of this code is:

1 2 3 4
5 6 7 8
9 10 11 12

It is important to note that two-dimensional arrays are just one way to represent a matrix or table of values in Java. There are other ways to achieve the same effect, such as using a one-dimensional array and calculating the indices, or using a class or data structure to represent a matrix. The choice of which approach to use will depend on the specific requirements of your program.

Created Time:2017-11-01 22:29:44  Author:lautturi