Question

As per this answer here

both java objects and primitives go on heap. So from the point of view of JVM, are objects and primitives similar except thaty objects take more space on the heap? In essence, are primitives nothing but 'light' objects?

Was it helpful?

Solution

Java primitives are not "light objects". They are primitives. They fail as objects in two very significant ways: they cannot go into Collection objects and they do not have methods.

They also do not go on the heap, except as fields of an actual Java object. You cannot do new int. Note also that when you declare a local variable that is of a primitive type, the variable comes into existence. When you declare a local variable of an object type, all you get is a reference to an object, but it is set to null and no object of the declared type is allocated by simply declaring the variable.

Note that autoboxing blurs the distinction somewhat, but the distinction is definitely there.

OTHER TIPS

There is a bit of confusion here. The question you're linking to in your question says that primitives inside an object can be in the heap. Primitives can't be in the heap by themselves.

You can't have an int referenced like an object, they are accessed directly without being "dereferenced".

You're extrapolating the fact that primitives could go in heap (as part of other objects) to conclude they could be light-weight objects. A set of primitives make up the state of an Object. They're not objects by themselves.

Primitives just have a value. They don't have a state and behaviour like Objects do. They don't exhibit inheritance, polymorphism etc. They don't behave like entities but like their attributes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top