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!
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!
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:
return new SomeType[] {x, y}; is valid but return {x, y}; is invalid.new SomeType[] {..} and {..} (not specifically during assignment), and I commented on the wrong question. I'm sorry.SomeType object = SomeFunction() is still initialization of object from a function which returns SomeType.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];