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

valueOf method

jai ahuja

Joined: May 17, 2012
Posts: 4
Hello sir,
my question is why there is valueOf method in wrapper classes...because same work is done bye new statement(instantiation - Integer a=new Integer(25);) also.
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

This is what the documentation for that method says (see java.lang.Integer#valueOf(int)):
If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

When you use new you force a new object to be created. Using valueOf allows the runtime to perform optimisations by reusing objects.
I agree. Here's the link:
subject: valueOf method
jQuery in Action, 3rd edition