DRAFT
ArrayAllocationWithoutNew
Misconception:
To allocate an array, one does not need to use new
.
E.g., Integer[3]
creates a new array of Integer
of length 3.
Incorrect
Arrays are created without the new keyword
Correct
All arrays are allocated on the heap with new
CorrectionHere is what's right.
Here is what's right.
Arrays are allocated on the heap.
They are a special kind of object.
To allocate them, one needs to use new
in almost all situations.
So, to allocate the above array, one needs to write new Integer[3]
.
char[] a;
a = new char[12]; // new required
a = new char[] {'A', 'B', 'C'}; // new required
However, there is an exception:
initializers in array variable declarations
do not need to specify the array type and the new
:
char[] a = new char[] {'A', 'B', 'C'};
char[] a = {'A', 'B', 'C'}; // ok