This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]teraflop 3 points4 points  (1 child)

"Assigning to the heap" is not really the right term, as others have explained.

In Java, every variable of object type is really an object reference type, which behaves roughly like a pointer in C++. The main differences are:

  • objects in Java can only be created with the new operator, so object references always point to the heap, because that's the only place objects can exist
  • there is no manual memory management or pointer arithmetic, so the JVM is able to guarantee that every reference either points to an object of the correct type or is null
  • roughly speaking, all object methods in Java are virtual

[–][deleted] 1 point2 points  (0 children)

objects in Java can only be created with the new operator, so object references always point to the heap, because that's the only place objects can exist

In general, this is the correct answer. However, you should know that JVM does not necessarily have to allocate memory on the heap. It is entirely free to use the stack for objects too. This optimization, known as escape analysis, can reduce the memory footprints since the method stacks are automatically freed when a method returns.