educative.io

Educative

There is a mistake - Regarding initialization of two dimensional arrays

class TwoDArray {
public static void main( String args[] ) {
int [][] my2DArray = new int[3][4];

  // add "10" at Row 0 and Column 1
    my2DArray[0][1] = 10;
    System.out.println(my2DArray[0][1]);
}

}

This code is working fine and the answer is 10;

Thank you for reaching out to us. Since, the code is working could you maybe highlight what the exact problem is?

The content says that the code should not work. But the code works.

Hi Vinary Maddi,

“Can you look at the following code and point out what’s wrong?”

The content is talking about the code written below this line and we were looking the code, written above the line. The code mentioned below is not working. Please have a look again and keep sharing your valuable feedback.

Thank You

“Can you look at the following code and point out what’s wrong?”

class TwoDArray {

public static void main( String args[] ) {

int[][] myArray = new int[10][10] ;
for (int i = 0; i < 10; i++)
{  
  for (int j = 0; j < 10; j++){
    myArray[i][j] = i + j;     
    System.out.println(myArray[i][j]);  
  }
}

}
}

“The code given above will result in a NullPointerException . The reason is that in line 4 , we only allocate memory for the rows . You need to allocate memory for the columns as well.”

This section is wrong, please update this material for future people who use this