How to Create a Two-dimensional Array in Java


In this example, let’s us see how to create a two-dimensional array.

Source Code

package com.beginner.examples;

public class CreateTwoDimentsionalArray {

	public static void main(String[] args) {
		
		//Define a two-dimensional array
		int[][] twoD = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
		
		//It can be assigned by subscript
		twoD[0][1]=20;
		
		//Print this two-dimensional array
		for(int i = 0 ; i< twoD.length;i++)
		{
			System.out.print("twoD["+i+"]:");
			for(int j = 0;j<twoD[i].length;j++)
			{
				System.out.print(twoD[i][j]+" ");
			}
			System.out.println();
			
			
		}
		
		

	}

}

Output:

twoD[0]:1 20 3 4 
twoD[1]:5 6 7 8 
twoD[2]:9 10 11 12 
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments