aspose file tools
The moose likes Beginning Java and the fly likes How does one wrap a primitive manually????? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "How does one wrap a primitive manually?????" Watch "How does one wrap a primitive manually?????" New topic
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
    
    4
There is more discussion about cached values in this recent thread.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: How does one wrap a primitive manually?????
 
Similar Threads
How to convert string to int ?
Java and OOPs
Doubt on Type casting
casting - from Dan's mock casting1
Instantiating an interface