Thursday, May 25, 2006

Wrapper Class

check out the following code:-

Integer i=Integer.valueOf(1);
Integer j=Integer.valueOf("1");
System.out.println(i==j);
Boolean b1=Boolean.valueOf(true);
Boolean b2=Boolean.valueOf("true");
System.out.println(b1==b2);

output is :-false true. why?


The valueOf() method in Integer class returns distinct objects. Hence the first result is FALSE.

But, the interesting part with Boolean class is that, it returns a reference to Boolean.TRUE (or) Boolean.FALSE objects.

Notes from API:


public static Boolean valueOf(boolean b)
value is Returns a Boolean instance representing the specified boolean value. If the specified booleantrue, this method returns Boolean.TRUE; if it is false, this method returns Boolean.FALSE. If a new Boolean instance is not required, this method should generally be used in preference to the constructor Boolean(boolean), as this method is likely to yield significantly better space and time performance.

public static Boolean valueOf(String s)

Returns a Boolean with a value represented by the specified String. The Boolean returned represents the
value true if the string argument is not null and is equal, ignoring case, to the string "true".

Example: Boolean.valueOf("True") returns true.
Example: Boolean.valueOf("yes") returns false.

0 Comments:

Post a Comment

<< Home