This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 4344

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.
wood burning stoves
subject: valueOf method
Similar Threads
question about == in wrappers
How does one wrap a primitive manually?????