| Author |
How does one wrap a primitive manually?????
|
Varun Goenka
Ranch Hand
Joined: Mar 09, 2009
Posts: 37
|
|
Please tell me how can one accept a primitive, or for that matter cast a primitive into an object that represents these primitives.
What I do mean is putting say a primitive int in the class int???
Please elaborate.
|
From The Demon,
with love.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
Since Java 5.0, all wrapper classes have a static method called valueOf that takes a matching primitive; for instance, Integer.valueOf(int), Long.valueOf(long). In Java 1.4 and before, only Boolean had that method; for all others you have to use the constructor; for instance, new Integer(int).
One hint: use valueOf instead of new if you can, because valueOf can return cached values.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Varun Goenka
Ranch Hand
Joined: Mar 09, 2009
Posts: 37
|
|
What are cached values?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
|
A cached value in general is one value that you reuse. For example, Boolean has two cached values, Boolean.TRUE and Boolean.FALSE. Boolean valueOf will always return either Boolean.TRUE or Boolean.FALSE - therefore, no new objects are created.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32836
|
|
|
There is more discussion about cached values in this recent thread.
|
 |
 |
|
|
subject: How does one wrap a primitive manually?????
|
|
|