initialize 2d array java code example

Example 1: how to print a 2d array in java

for (int row = 0; row < arr.length; row++)//Cycles through rows
{
  for (int col = 0; col < arr[row].length; col++)//Cycles through columns
  {
    System.out.printf("%5d", arr[row][col]); //change the %5d to however much space you want
  }
  System.out.println(); //Makes a new row
}
//This allows you to print the array as matrix

Example 2: arrays sort 2d array java

Arrays.sort(myArr,(double[] a,double[] b)->{
                //here multiple lines of code can be placed
                return a[0]-b[0]; 
            });

Example 3: 2d array java

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

Example 4: two dimensional array in java example program

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

        int[][] a = {
            {1, -2, 3}, 
            {-4, -5, 6, 9}, 
            {7}, 
        };
      
        for (int i = 0; i < a.length; ++i) {
            for(int j = 0; j < a[i].length; ++j) {
                System.out.println(a[i][j]);
            }
        }
    }
}

Example 5: 2d array java

//Length
int[][]arr= new int [filas][columnas];
arr.length=filas;

        int[][] a = {
            {1, 2, 3}, 
            {4, 5, 6, 9}, 
            {7}, 
        };
      
        // calculate the length of each row
        System.out.println("Length of row 1: " + a[0].length);
        System.out.println("Length of row 2: " + a[1].length);
        System.out.println("Length of row 3: " + a[2].length);
    }

Example 6: two dimensional array in java example program

String[][][] data = new String[3][4][2];

Tags:

C Example