Ariel
Ariel

Reputation: 161

Array initialization differences 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!

Upvotes: 10

Views: 1415

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1500595

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:

Upvotes: 22

abhihello123
abhihello123

Reputation: 1728

There is a small and catchy difference still!

You can do

int[] arr;
arr= {1,2,3}; // Illegal

But you can very well do

int[] arr;
arr = new [] {1,2,3} //Legal

Also if you are to initialize later then you cannot do

int arr;
arr = new [] {1,2,3} //Illegal

Upvotes: 0

Feras Odeh
Feras Odeh

Reputation: 9296

In Java all objects live in the heap, as arrays are objects in Java they lives in the stack.

for these two there is no difference in result, you 'll got two array objects with the same elements.

However sometimes you will encounter some situations where you can't use them, for example you don't know the elements of the array. then you get stuck with this form:

Object [] array=new Object[size];

Upvotes: 1

Highland Mark
Highland Mark

Reputation: 1010

Absolutely identical. The second is allowed shorthand for the first (only when, as here, it is done as part of a variable declaration.

Upvotes: 2

Related Questions