java two-dimensional array code example

Example 1: Multidimensional array in java

// two dimensional string array in java example
public class TwoDimensionalStringArray 
{
   public static void main(String[] args) 
   {
      String[][] animals = {
              { "Lion", "Tiger", "Cheetah" },
              { "Deer", "Jackal", "Bear" },
              { "Hyena", "Fox", "Elephant" } };
      for(int a = 0; a < animals.length; a++) 
      {
         System.out.print(animals[a][0] + " ");
         for(int b = 1; b < animals[a].length; b++) 
         {
            System.out.print(animals[a][b] + " ");
         }
         System.out.println();
      }
   }
}

Example 2: 2d array java

char[][] array = new int[rows][columns];

Example 3: How to create a 2d array in java

int[][] arr = new int[m][n];

Example 4: two dimensional array in java example program

class MultidimensionalArray {
    public static void main(String[] args) {

        // create a 2d array
        int[][] a = {
            {1, -2, 3}, 
            {-4, -5, 6, 9}, 
            {7}, 
        };
      
        // first for...each loop access the individual array
        // inside the 2d array
        for (int[] innerArray: a) {
            // second for...each loop access each element inside the row
            for(int data: innerArray) {
                System.out.println(data);
            }
        }
    }
}

Tags:

Cpp Example