What does the `new` keyword do

In Java, all arrays and objects are allocated on the heap, so in a sense, all arrays are “array objects”. The only things that are ever allocated on the stack in Java are object references and primitives. Everything else is an object that is defined and allocated in the heap, including arrays, regardless of which syntax you use to declare it. (Your two examples are equivalent in the end result, see JLS ยง10.3 and its linked sections for more on how each one is actually allocated and assigned.)

This is contrary to C/C++, where you have explicit control over stack and heap allocation.

Note that Java is very fast when it comes to short-term object allocation/deallocation. It’s highly efficient because of its generation-based garbage collector. So to answer your questions:

Are there certain “array” specific methods that won’t work on an array unless it’s an “array object”? Is there anything that I can’t do with an “array object” that I can do with a normal array?

There is no such thing as an array that’s not an object, so no. There are, however, methods which won’t work on primitive arrays. A method that takes an Object[] will not accept a long[] without first converting it to Long[]. This is due to some implementation details of autoboxing in Java 5 and up.

Does the Java VM have to do clean up on objects initialized with the new operator that it wouldn’t normally have to do?

Anything allocated with new must eventually be garbage collected, so in terms of doing anything it wouldn’t normally do? No. However, note that in C/C++, allocating an array using malloc/new means you also have to free/delete [] it, which is something you don’t have to do in Java since it will reclaim the array for you.

Note that if your long[] is declared in a method, and you never store it in a reference somewhere outside of your method, it will be marked for garbage collection automatically at the end of the method call. The garbage collector will wait to reclaim its space until it needs it, but you don’t have to do any reclamation yourself via delete [] (or delete and destructors for objects).

Edit: some references as promised:

Leave a Comment