• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Wrapping primitives using the new operator vs wrapping primitives using valueOf  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am reading SCJP Exam for J2SE 5 by Paul Sanghera and am confused about something. I am reading on the different methods of wrapping primitives with a wrapper object and the book presents 2:

1. Using the new operator like

Integer myInt = new Integer(4)

2. Using the static valueOf method of the wrapper class like:

Integer myInt = Integer.valueOf(4).

What are the reasons to use one method versus the other? It seems to me like these 2 methods of creating the wrapper object for a primitive are equivalent alternatives, but in the book it suggests:

"There will be situations in your program when you really don't need a new instance of the wrapper class, but you still want to wrap a primitive. In this case, pass the primitive type as an argument to the static method valueOf() of the corresponding wrapper class."

The thing confusing about this is that I thought both methods *DO* in fact create a new instance of the wrapper class.

Any help would be appreciated.

Warm Regards,
Nilay
 
author
Sheriff
Posts: 23589
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The valueOf() method that takes a primative int, was added in Java 5, mainly to support autoboxing. Boxing uses the valueOf() method, because the valueOf() method doesn't always create a new instance -- it also maintains a cache.

Henry
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!