dynamic initialization of 2d array in java code example

Example 1: Create dynamic 2d array in java

// Create dynamic 2d array in java
import java.util.ArrayList;
import java.util.List;
public class Dynamic2dArray 
{
   public static void main(String[] args) 
   {
      List<int[]> li = new ArrayList<>();
      li.add(new int[]{2,4,6});
      li.add(new int[]{3,5});
      li.add(new int[]{1});
      // element at row 0, column 0
      System.out.println("Element at [0][0]: " + li.get(0)[1]);
      // get element at row : 1, column : 1
      System.out.println("Element at [1][1]: " + li.get(1)[1]);
   }
}

Example 2: Java 2d array initialization

class TwoDimensionalArray {

    public static void main(String[] args) {
        String[][] salutation = {
            {"Mr. ", "Mrs. ", "Ms. "},
            {"Kumar"}
        };

        // Mr. Kumar
        System.out.println(salutation[0][0] + salutation[1][0]);

        // Mrs. Kumar
        System.out.println(salutation[0][1] + salutation[1][0]);
    }
}

The output from this program is:

Mr. Kumar
Mrs. Kumar