Write a Java Program to convert primitive types to objects and vice versa

Java is an object-oriented programming language that supports both primitive data types and object data types.

In some situations, it may be necessary to convert primitive data types to object data types, or vice versa.

In this tutorial, we will explore how to convert between primitive types and object types in Java.


Converting Primitive Types to Objects

To convert a primitive data type to its corresponding object type, we can use a process called “boxing.”

This process involves wrapping the primitive value in an object of the corresponding type.

The following code demonstrates how to box a primitive type:

int myInt = 10;
Integer myInteger = Integer.valueOf(myInt);

In this code, we create an integer variable myInt with the value 10.

We then use the valueOf() method of the Integer class to create a new Integer object, myInteger, that wraps the value of myInt.

Java also provides a shorthand notation for boxing primitive values.

We can simply assign a primitive value to a variable of its corresponding object type, and Java will automatically box the value for us:

int myInt = 10;
Integer myInteger = myInt;

In this code, we assign the value of myInt to the myInteger variable, which is of type Integer.

Java automatically boxes the value for us.

Converting Objects to Primitive Types

To convert an object of a corresponding type to a primitive data type, we can use a process called “unboxing.”

This process involves extracting the primitive value from the object.

The following code demonstrates how to unbox an object:

Integer myInteger = Integer.valueOf(10);
int myInt = myInteger.intValue();

In this code, we create an Integer object myInteger with the value 10.

We then use the intValue() method of the Integer class to extract the primitive value from myInteger and assign it to the myInt variable.

Java also provides a shorthand notation for unboxing object values.

We can simply assign an object value to a variable of its corresponding primitive type, and Java will automatically unbox the value for us:

Integer myInteger = Integer.valueOf(10);
int myInt = myInteger;

In this code, we assign the myInteger object to the myInt variable, which is of type int.

Java automatically unboxes the value for us.


Conclusion

Converting between primitive types and object types in Java is a straightforward process that involves boxing and unboxing.

We can use the valueOf() method to box primitive types, and we can use the corresponding xxxValue() methods to unbox object types.

Alternatively, we can use the shorthand notation to let Java automatically perform the conversion for us.

Understanding how to convert between primitive types and object types is an essential skill for any Java programmer.