This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes toString Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "toString" Watch "toString" New topic
Author

toString

nachagoni rishi
Greenhorn

Joined: Oct 14, 2004
Posts: 26
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

Joined: Aug 03, 2002
Posts: 7729
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.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
nachagoni rishi
Greenhorn

Joined: Oct 14, 2004
Posts: 26
Thank you for the explanation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: toString