File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes valueOf().. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "valueOf().." Watch "valueOf().." New topic


Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Hi, I got it from

class Boo
public static void main(String args[])
Boolean b1 = Boolean.valueOf(true);
Boolean b2 = Boolean.valueOf(true);
Boolean b3 = Boolean.valueOf("TrUe");
Boolean b4 = Boolean.valueOf("tRuE");
System.out.print((b1==b2) + ",");
System.out.print((b1.booleanValue()==b2.booleanValue()) + ",");


output is true,true,true.
I thought the answer would be false,true,false. Since the valueOf() returns newly createdobject of the type that invoked the method.

please explain me this comes true...

thanks in advance
Preparing Scjp 1.5
Ankit Garg

Joined: Aug 03, 2008
Posts: 9462

Originally posted by Preetha Arun:
valueOf() returns newly createdobject of the type that invoked the method.

No value of returns objects from the pool. when you use new Type() syntax, then you get a new object. In autoboxing you get a value from the pool(it it's in the range) because autoboxing uses type.valueOf internally...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Graeme Jenkinson

Joined: Sep 08, 2008
Posts: 27
Just to add my 2 cents.

"valueOf" methods are static factory methods. They provide an alternative mechanism for instatiating objects (they are used in a number of places including the wrapper classes). One of their benefits is that they allow the flexibility to determine whether a new instance is created or whether a reference to a previously created instance (from a previosly allocated pool) is returned (this is being an implementation of the Flyweight pattern). In this example the boolean Wrapper class (Boolean) can return the same reference when invoked with Boolean.value("true") without the need to actually create an new object each time. Depending on the exact nature of the program this can potentially add up to a very singificant saving in memory. It is certainly a value tool to understand and apply prudently when your putting Java to work (for more info see Effective Java).

(P.S. I found that understanding the context helped me to remember what valueOf methods took as parameters and what types they returned)


Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Thanks to you both. I got it

Preparing Scjp1.5
I agree. Here's the link:
subject: valueOf()..
It's not a secret anymore!