wood burning stoves*
The moose likes Beginning Java and the fly likes toString method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "toString method" Watch "toString method" New topic
Author

toString method

venkatesh pendharkar
Ranch Hand

Joined: Apr 29, 2006
Posts: 106
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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Apr 29, 2006
Posts: 106
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: toString method