• Post Reply Bookmark Topic Watch Topic
  • New Topic

It's not returning the Address  RSS feed

 
Arun C. Giridharan
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's problem with this code it's not returning the address of the object s1 ?
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why should it return the Address? That's the default if the class does not have a toString() method.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What else would you expect the toString() method of a string to return?
 
Arun C. Giridharan
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But s1 is the reference variable,so it must return the address of s1 ,right?

like String@hex
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arun Giridharan wrote:But s1 is the reference variable,so it must return the address of s1 ,right?

like String@hex


The default toString() methid returns the type and the hashcode. And as already mentioned in your other topic, that there is little to no relationship with the address. And for the string class, there is absolutely no relationship with the address.

Henry
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read the API doc for println() to see how it treats Strings and Objects:
otherwise, the value of obj.toString() is returned.
 
Bala Gangadhar
Ranch Hand
Posts: 119
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Arun,
Its very simple...
The println always calls the .toString method if it encounters a reference variable (s1 in our case).

The toString() method is declared in java.lang.Object class with default behavior of returning className@hashCode
But in String class the toString() method is overridden to return the actual string of characters it is representing ( "Hello" in our case).



Regards,
Bala.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use System.identityHashCode, but that still doesn't give you the memory address of the String. Java simply hides this information from you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!