1.A] What is Autoboxing? Write a Java program that demonstrates how autoboxing and unboxing take place in expression evaluation
Answer:
Autoboxing and Unboxing
Autoboxing is the automatic conversion that the Java compiler makes between the primitive data types (e.g., int
, char
, boolean
, etc.) and their corresponding object wrapper classes (e.g., Integer
, Character
, Boolean
, etc.).
Unboxing is the reverse process, where the object wrapper class is automatically converted back to the corresponding primitive type.
Example:
- Autoboxing: Converting an
int
to anInteger
. - Unboxing: Converting an
Integer
to anint
.
Java Program Demonstrating Autoboxing and Unboxing in Expression Evaluation:
public class AutoboxingUnboxingDemo { public static void main(String[] args) { // Autoboxing: Primitive int is automatically converted to Integer object Integer intObj = 10; // Unboxing: Integer object is automatically converted to primitive int int intVal = intObj; // Autoboxing in expression evaluation Integer result = intObj + 5; // intObj is unboxed to int, then added to 5, and then autoboxed to Integer // Displaying the results System.out.println("Integer object (Autoboxed from int): " + intObj); System.out.println("Primitive int (Unboxed from Integer): " + intVal); System.out.println("Result after expression evaluation (Autoboxed to Integer): " + result); } }
Explanation:
Autoboxing:
Integer intObj = 10;
- Here, the primitive
int
value10
is automatically converted to anInteger
object.
- Here, the primitive
Unboxing:
int intVal = intObj;
- Here, the
Integer
objectintObj
is automatically converted back to the primitiveint
value.
- Here, the
Expression Evaluation:
Integer result = intObj + 5;
- The
intObj
is unboxed to anint
for the addition operation with5
. - The result of the addition, a primitive
int
, is then autoboxed back into anInteger
object and stored inresult
.
- The
This program effectively demonstrates how autoboxing and unboxing work in Java, particularly within the context of expression evaluation.