Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization differences java

Tags:

java

What is the difference between the two following methods of array initialization:

  1. Object[] oArr = new Object[] {new Object(), new Object()};
  2. Object[] oArr = {new Object(), new Object()};

Is it related to heap/stack allocation?

Thanks!

like image 663
Ariel Avatar asked Jan 16 '11 17:01

Ariel


People also ask

What are the different ways of initializing array?

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.

What is the difference between array initialization and declaration?

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.

What are the two ways to initialize an array of three values?

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.


1 Answers

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:

like image 62
Jon Skeet Avatar answered Sep 30 '22 05:09

Jon Skeet