Object - an instance of a class which resides in Heap memory.

Types with respect to Object

An object has a true runtime type, determined by what constructor was used with "new." It also has supertypes (unless the true runtime type happens to be the base class, java.lang.Object). In this sense, an object can have many types.

A reference also has a type, which must be the type of the object it's pointing to, or any of that object's supertypes.

So rather than talking about the "object" having "two" types, I think it's important to distinguish between the reference type and the object's true runtime type.

Where do the variables live?

This is an usual question comes to local variable, reference variable, instance variable, class variable and with the stack andheap memory.

One of the bartenders Jim Yingst edited to my reply in the forum.

[Raghavan Muthu]: The objects do certainly live in the Heap memory.

Not always. Since JDK 6 the JVM will sometimes allocate objects on the stack instead, if it can determine that the object is only accessible from within the current method. This is called escape analysis.

[Raghavan Muthu]: And the references are like another variables, they are supposed to live in Stack Memory.

I think Anders was asking about references like the variable s, which is an instance variable. (Even though it's also a constant.) Instance variables generally exist on the heap, as part of the instance. Unless the instance is on the stack, as just discussed.

Local variables are always on the stack. Instance variables are located with the instance, generally on the heap. Class (static) variables are located with the Class object, which should be always on the heap.

In general though, you don't really need to know or care where a Java object exists in memory. If it helps your understanding to know this stuff, great. But if it gets confusing, it really doesn't matter anyway, unless you're building your own JVM.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.