Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString()

 
Ram Murthy
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1: Byte b1 = new Byte("127");
2:
3: if(b1.toString() == b1.toString())
4: System.out.println("True");
5: else
6: System.out.println("False");

A) Compilation error, toString() is not avialable for Byte.
B) Prints "True".
C) Prints "False".

The o/p is C.

Why <<b1.toString() == b1.toString()>> not true ??

Thanks,
JP
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Each call to the toString() method returns a new distinct String object. Two distinct objects are not "==" to each other.
 
Ram Murthy
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried the below code ...

Byte b1 = new Byte("127");
System.out.println(b1.toString());
System.out.println(b1.toString());

Both the SOP's returned 127, I don't see what is distinct here ??

Regards,
JP
 
Kevin Lam
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But when you compare with ==, it compares the "reference address"

Although two Strings contains the same letters, but it is two different objects, hence two different addresses.

If you compare them with equals(), that will return you true because that compares the content of the two strings instead of the address.

Hope this helps

Kev
 
Abdulla Mamuwala
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ravi,
Each call to the toString() method returns a new distinct String object. Two distinct objects are not "==" to each other.

What Barry meant above is that the "==" checks for reference equality and not for equality of what the Byte objects hold in this case the value 127.
Let's look at the following code diagramatically,

Byte b1 = new Byte("127");
A object is created on the heap with reference A0


System.out.println(b1.toString());
The code above will create a new object on the heap, with reference A2


System.out.println(b1.toString());
The code above will create a new object on the heap, with reference A3


As you can see the references A2 and A3 are not the same, therefore '==' returns false.
 
Ram Murthy
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic