Reputation: 1208
I just started to learn Java and I want to ask you a question about Integer objects.
For example we have:
Integer i = new Integer(15);
Why I can't see the memory address if I type System.out.println(i)?
I know that if I want to see the memory address for any object I type S.O.P(obj) and i see a memory address like projectname.classname@4141d797 and this is stored in stack, because for reference types, the stack holds a pointer to the object on the heap.
And I see that this is not working for Integer objects. If I type S.O.P(i) I receive 15.
Why in this case the stack doesn't hold the memory address to the object on the heap?
Thanks in advance!
Upvotes: 2
Views: 1605
Reputation: 9437
You only see a memory address for datatypes that do not provide a correct implementation of toString();
These types inherit the default behaviour of the Object
class, which is: https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString--
Upvotes: 0
Reputation: 633
When you try print an object using the System.out.println
command what really happens is a call to the toString
method of that object. All objects implicitly extend the class Object, whose toString
method returns the output you're familiar with.
However in the case of Integer class the toString
is overriden and is returning the value of the Integer instead. That's because if you're printing out an Integer it's very likely you just want to learn the number it represents, not the String representation of the object
Upvotes: 1
Reputation: 73578
Because Integer
overrides the default Object.toString()
method which gives you the particular output you're thinking about.
It's not even strictly a memory address, even though the current implementation does use the address as the basis for it. However objects can be moved around in memory and that value won't change, so you can't really draw any conclusions from it.
Lastly, you shouldn't care about it. You don't need to worry about where objects are stored with Java.
Upvotes: 3