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.
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.