Take the 2-minute tour ×

So I went over this block of code several times in a book that I'm reading:

int[][] someArray = new int[size][];
   someArray[i] = new int[size];

I don't see any difference between that and the following declaration:

int[][] someArray = new int[size][size];

Did I miss anything here? Is there any reason why I should use the long block of code above?


share|improve this question

4 Answers 4

up vote 6 down vote accepted

You can create ragged or jagged arrays with the first construct

share|improve this answer
+1 for mentioning ragged arrays. But in the example above, the two arrays would be arrays of identical dimensions (size * size). But imagine that in the first code snippet, you change 'someArray[i] = new int[i]'. Notice that instead of 'new int[size]', I put 'new int[i]' That's what this allows you to do, and that's a ragged array! –  Zaki Saadeh Nov 8 '11 at 2:37
yeah, I would understand that if they give different size in the for loop but they use the same 'size'. So it doesn't make any sense to me at all.' –  chepukha Nov 8 '11 at 2:39
You are correct. If you creating m*n array it doesn't make sense to do it the first way. I was just mentioning what the potential difference could ge –  parapura rajkumar Nov 8 '11 at 11:46

As said by parapura you can create what's called a ragged array. Essentially you can make something triangular shaped and such (might resemble stairs or a christmas tree or whatever you want it to be). So it can be like (using random numbers)

1 2 3

1 2

4 4 5 6 2 3 5

4 5 1

2 2 5 2

where the lengths of the sub arrays are different sizes. In your example though they are both the same size so both ways do exactly the same thing.

One reason this could be done is to save space in memory instead of zero filling empty slots.

share|improve this answer

No difference here. The first one is useful when we want to create arrays having different sizes.

share|improve this answer

When in doubt take a look at the bytecode -- especially for something like this that is just a few lines of code.
Apparently the compiler has a special construct for creating the second form.

first form (without the loop): public static void main(java.lang.String[]); Code: 0: iconst_3 1: anewarray #2; //class "[I" 4: astore_1 5: return

second form:

0: iconst_3 1: iconst_3 2: multianewarray #2, 2; //class "[[I" 6: astore_1 7: return


One way to look at it is that there is a LOT of wasted time in the loop when you know you are going to have a "square" array anyways. Imagine if you were at Google and you needed a two-dimensional array with size=10000000. The first form would be dramatically slower.

share|improve this answer

Your Answer


