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
intto anInteger. - Unboxing: Converting an
Integerto 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
intvalue10is automatically converted to anIntegerobject.
- Here, the primitive
Unboxing:
int intVal = intObj;- Here, the
IntegerobjectintObjis automatically converted back to the primitiveintvalue.
- Here, the
Expression Evaluation:
Integer result = intObj + 5;- The
intObjis unboxed to anintfor the addition operation with5. - The result of the addition, a primitive
int, is then autoboxed back into anIntegerobject and stored inresult.
- The
This program effectively demonstrates how autoboxing and unboxing work in Java, particularly within the context of expression evaluation.
