This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString method

 
venkatesh pendharkar
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
i was trying th following code:
class D
{
void met()
{
Byte b=new Byte("111");
System.out.println(b.toString()==b.toString());
}

public static void main(String[] args)
{
D d=new D();
d.met();
}
This will print "false" as "==" method compares memory address of objects & toString() returns a String object representing the primitive value.
But in the above code ;instead of Byte b=new Byte("111"); we write it as Boolean b=new Boolean("true"); then we get output as "true".

Why is it so that if we take boolean object the "==" method returns true but for any other wrapper object it returns "false".
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from the API docs for Boolean.

toString

public static String toString(boolean b)

Returns a String object representing the specified boolean. If the specified boolean is true, then the string "true" will be returned, otherwise the string "false" will be returned.

Parameters:
b - the boolean to be converted
Returns:
the string representation of the specified boolean
Since:
1.4



This is from the API docs for Byte.

toString

public String toString()

Returns a String object representing this Byte's value. The value is converted to signed decimal representation and returned as a string, exactly as if the byte value were given as an argument to the toString(byte) method.


toString

public static String toString(byte b)

Returns a new String object representing the specified byte. The radix is assumed to be 10.


So the toString() method of Byte returns a new String object representing the Byte, but a Boolean object will return a reference to either the String literal "true" or the String literal "false".
 
venkatesh pendharkar
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Keith for your help.Actually I am preaparing for SCJP exam & i came across this question in one of the Mocks.
Hey if possible can you send me any links which are good for SCJP preaparation
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic