wood burning stoves 2.0
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "toString" Watch "toString" New topic


nachagoni rishi

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("Not Equal");


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

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

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