Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString

 
nachagoni rishi
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can u please explain me why the following to codes have different answers.


Read this piece of code carefully

if("String".toString() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

Answers


the code will compile an print "Equal".
the code will compile an print "Not Equal".
the code will cause a compiler error.



Ans is 1.



The following code will give

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".

ans:c
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you read the String API you will see that toString is documented as:
This object (which is already a string!) is itself returned.


So "String".toString() is the same object as "String". Remember that strings like "String" are stored in a string literal pool. Because we are comparing identical string literals the result of the "==" operator is true.

Byte.toString() returns a new String object every time it is called. And the objects returned are not the original string literal "127". So the "==" comparison fails.
 
nachagoni rishi
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the explanation
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic