What is Autoboxing? Write a Java program that demonstrates how autoboxing and unboxing take place in expression evaluation

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., intcharboolean, etc.) and their corresponding object wrapper classes (e.g., IntegerCharacterBoolean, 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 an Integer.
  • Unboxing: Converting an Integer to an int.

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 value 10 is automatically converted to an Integer object.

Unboxing:

  • int intVal = intObj;
    • Here, the Integer object intObj is automatically converted back to the primitive int value.

Expression Evaluation:

  • Integer result = intObj + 5;
    • The intObj is unboxed to an int for the addition operation with 5.
    • The result of the addition, a primitive int, is then autoboxed back into an Integer object and stored in result.

This program effectively demonstrates how autoboxing and unboxing work in Java, particularly within the context of expression evaluation.

Leave a Reply

Your email address will not be published. Required fields are marked *