Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

valueOf method

 
jai ahuja
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 4566
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic