• Post Reply Bookmark Topic Watch Topic
  • New Topic

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: 23503
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
 
when your children are suffering from your punishment, tell your them it will help them write good poetry when they are older. Like this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!