This example shows how to convert Java primitive data types to respective wrapper class objects like int to Integer object, long to Long object, float to Float object, double to Double object, byte to Byte object, short to Short object and char to Character object.
How to convert a primitive data type to a wrapper object in Java?
There are a couple of ways in which Java primitive data types can be converted to respective wrapper objects.
1) Using a wrapper class constructor
Each wrapper class provides a constructor that accepts respective primitive value as an argument and creates a wrapper object around it as given in the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
public class PrimitiveToWrapperExample { public static void main(String[] args){ char c = 'a'; Character cObj = new Character(c); System.out.println("char to Character object: " + cObj); byte b = 18; Byte bObj = new Byte(b); System.out.println("byte to Byte object: " + bObj); short s = 345; Short sObj = new Short(s); System.out.println("short to Short object: " + sObj); int i = 4323; Integer intObj = new Integer(i); System.out.println("int to Integer object: " + intObj); long l = 232567l; Long lObj = new Long(l); System.out.println("long to Long object: " + lObj); float f = 523.34f; Float fObj = new Float(f); System.out.println("float to Float object: " + fObj); double d = 43243.65432d; Double dObj = new Double(d); System.out.println("double to Double object: " + dObj); } } |
Output
1 2 3 4 5 6 7 |
char to Character object: a byte to Byte object: 18 short to Short object: 345 int to Integer object: 4323 long to Long object: 232567 float to Float object: 523.34 double to Double object: 43243.65432 |
2) Using Autoboxing (Java 1.5 and later)
The autoboxing feature is introduced in Java 1.5 version which automatically converts a primitive value to the respective wrapper object automatically. That means, you can directly assign a primitive value or a variable to respective wrapper class object and conversion is done automatically as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
char c = 'a'; Character cObj = c; byte b = 18; Byte bObj = b; short s = 345; Short sObj = s; int i = 4323; Integer intObj = i; long l = 232567l; Long lObj = l; float f = 523.34f; Float fObj = f; double d = 43243.65432d; Double dObj = d; |
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.