toString method

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

posted 10 years ago

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

posted 10 years ago

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