What is the difference between the two following methods of array initialization:
Object[] oArr = new Object[] {new Object(), new Object()};
Object[] oArr = {new Object(), new Object()};
Is it related to heap/stack allocation?
Thanks!
There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.
Answer. Array declaration tells the compiler about the size and data type of the array so that the compiler can reserve the required memory for the array. This reserved memory is still empty. Array Initialisation assigns values to the array elements i.e. it stores values in the memory reserved for the array elements.
How to Declare and Intialize an Array in Java. There are two ways you can declare and initialize an array in Java. The first is with the new keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.
None at all - they're just different ways of expressing the same thing.
The second form is only available in a variable declaration, however. For example, you cannot write:
foo.someMethod({x, y});
but you can write:
foo.someMethod(new SomeType[] { x, y });
The relevant bit of the Java language specification is section 10.6 - Array Initializers:
An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With