java

How to Declare and Initialize two dimensional Array in Java

In this tutorial, we are going to see how to declare and Initialize two dimensional Array in Java.
 

Example 1: Program to Declare and Initialize two dimensional Array of integers in Java
public class Main {

    public static void main(String[] args) {

        int[][] arr2D = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };
		
        int j, i = 0;

        for (int[] arr1D : arr2D) {
            j = 0;
            for (int val : arr1D) {
                System.out.println("[" + i + "][" + j + "] = " + val);
                j++;
            }
            i++;
        }
    }
}

Output:

[0][0] = 1
[0][1] = 2
[0][2] = 3
[1][0] = 4
[1][1] = 5
[1][2] = 6
[2][0] = 7
[2][1] = 8
[2][2] = 9
 

Example 2: Program to Declare and Initialize two dimensional Array of String in Java
public class Main {
	
 public static void main(String args[]) {
	 
  // Declare and initialize a 2D array
  String[][] names = { 
	     {"Alex", "Bob", "Thomas"}, 
	     {"Emily", "Jean", "James"}, 
	     {"Ali", "Yohan", "Camilia"} 
  };

  // Display the 2D array
  for (String[] arr: names) {
     for (String s: arr) {
         System.out.print(s + "\t");
     }
     System.out.println("\n");
  }
 }
}

Output:

Alex	Bob	Thomas	

Emily	Jean	James	

Ali	Yohan	Camilia
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *