DEV Community

Abhishek Kumar
Abhishek Kumar

Posted on

A program that demonstrates autoboxing and unboxing with ArrayList and arithmetic operations.

Here's a Java program that demonstrates autoboxing and unboxing with an ArrayList and arithmetic operations:

import java.util.ArrayList;

public class AutoboxingUnboxingExample {

    public static void main(String[] args) {
        // Create an ArrayList of Integer (Wrapper class for int)
        ArrayList<Integer> numbers = new ArrayList<>();

        // Autoboxing: Adding primitive int to the ArrayList, automatically converted to Integer
        numbers.add(10);  // Autoboxing (int -> Integer)
        numbers.add(20);  // Autoboxing
        numbers.add(30);  // Autoboxing

        // Display the contents of the ArrayList
        System.out.println("ArrayList: " + numbers);

        // Unboxing: Retrieving values from ArrayList, Integer to int
        int sum = 0;
        for (Integer num : numbers) {
            sum += num;  // Unboxing happens here (Integer -> int)
        }

        // Print the sum of elements
        System.out.println("Sum of ArrayList elements: " + sum);  // Output: Sum of ArrayList elements: 60

        // Autoboxing and Unboxing in arithmetic operations
        Integer a = 100;  // Autoboxing (int -> Integer)
        Integer b = 200;  // Autoboxing
        int result = a + b;  // Unboxing (Integer -> int) during addition
        System.out.println("Result of a + b: " + result);  // Output: Result of a + b: 300

        // Example of Unboxing with direct assignment
        int c = numbers.get(0);  // Unboxing (Integer -> int)
        System.out.println("First element in ArrayList (unboxed): " + c);  // Output: First element in ArrayList (unboxed): 10
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Autoboxing: Occurs when primitive values (like 10, 20, 30) are automatically converted to their wrapper class (Integer) when added to the ArrayList (which only accepts objects).
  • Unboxing: Happens when values are retrieved from the ArrayList and used in arithmetic operations (like summing or direct assignments), automatically converting Integer objects back to int.

Output:

ArrayList: [10, 20, 30]
Sum of ArrayList elements: 60
Result of a + b: 300
First element in ArrayList (unboxed): 10
Enter fullscreen mode Exit fullscreen mode

This program effectively shows how autoboxing and unboxing work in Java.

Top comments (0)