• Post Reply Bookmark Topic Watch Topic
  • New Topic

How does one wrap a primitive manually?????  RSS feed

 
Varun Goenka
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Varun Goenka
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are cached values?
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is more discussion about cached values in this recent thread.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!