The reason is that Java's designers wanted to ensure that it's very clear what type the array has. If the type "int" appears on the same line as the array, that's fine. But once you try to separate them, the designers felt that would make it too hard for the reader to reliably tell what the type was. Of course it's easy if the lines are right next to each other, but harder if they're far apart. The compiler could tell either way, but for humans it's a bit harder.
I just read this further on in my studies....
The advantage of using the �new type[ ]� syntax is that it can be used in an assignment statement that is not a variable declaration statement.
It refers to the code in my first post. I'm not really sure I understand what it means. Can you try to explain it a little further?
This is an assignment to the same variable, with no declaration:
This is a declaration and assignment (initialization) as a single statement:
You can omit the "new int" only in the last case. In the second example above, you must include the "new int".
Welcome to JavaRanch!
An array is a fixed-size thing; a java.util.ArrayList is... well, it's what C#'s ArrayList is named after, and acts the same. Inside an ArrayList is an an array, and when the ArrayList grows, it does it by copying and reallocating arrays.
When you construct an array object, you must specify the size, either by providing a list of values (the topic of this thread) or just by providing a size, in which case you get an empty array with default-initialized elements (zero, null, false, etc.)
int tenZeroes = new int;
int someArray = new int; // I might not use all 10 indexes, but our code won't try to fill it passed the 10th index
Originally posted by Nathan Leniz:
If we have an array that we don't know what it's exact size will be after the code executes, but we do know it can't be larger than a certain size, is it safe practice to initialize it with what the maximum could be?
It's "safe" in the sense that nothing bad will automatically happen, but it's often awkward because you have to keep track of the 'real" length of the array, and remember not to write loops using array.length as your upper limit. It's fragile. In general, when you have to do this kind of thing, it makes sense to encapsulate it in a class of its own, so the touchy bookkeeping code can be tested and validated in isolation. That's exactly what java.util.ArrayList is -- a bigger-than-needed array, plus a size, plus all the code needed to manipulate them.