Assign values to two dimensional array in Java

Published by user on

In this post, we are going to look at different ways of assigning values to two dimensional array in Java.

Declare two dimensional array and assign value to elements

In this way, we assign the value to elements of two dimensional array during declaration.

Let’s look at the example.

int[][] myArray = {{10,20},{30,40}};

In the above example, we declared the two dimensional array and assigned the values to each element. Java automatically figures out the size of the array using the number of elements in each row.
This method is clear and concise.

Assign a value to each element using index

Here we declare the array using the size and then assign value to each element using the index.

Let’s have a look at the example:

public class AssignValueTwoDimensionalArray {
	public static void main(String[] args) {
		int[][] myArray = new int[2][2];

		// assign value to the first element
		// like wise assign values to all elements
		myArray[0][0] = 10;
		myArray[0][1] = 20;
		myArray[1][0] = 30;
		myArray[1][1] = 40;

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

As you can see we assigned the value to each element of the array using the index.

That’s all for assigning the value to two dimensional array.

Categories: Java