0 votes
1 view
in Java by (4.1k points)

Consider:

int[][] multD = new int[5][];

multD[0] = new int[10];

Is this how you create a two-dimensional array with 5 rows and 10 columns?

I saw this code online, but the syntax didn't make sense.

1 Answer

0 votes
by (46.1k points)

You can try this:

int[][] multi = new int[5][10];

It's short method for something like this:

int[][] multi = new int[5][];

multi[0] = new int[10];

multi[1] = new int[10];

multi[2] = new int[10];

multi[3] = new int[10];

multi[4] = new int[10];

Note that each element will be initialized to the default value for int, 0, so the above are also equivalent to:

int[][] multi = new int[][]{

  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },

  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },

  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },

  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },

  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

};

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...