Search code examples
javareferencepass-by-referenceboxingunboxing

What's the point of autoboxing primitives in Java?


What's the point of having Integer, Boolean etc and call them "...boxing" if they don't behave like boxed objects that you can pass "by ref" and do unboxing to change their value?

Here's an example of "unboxing" that I actually found out isn't really unboxing.

    public static void main(String[] args) {
        Boolean x = true;
        foo(x);
        System.out.println(x);

        Integer num = 9;
        bar(num);
        System.out.println(num);
    }

    private static void bar(Integer num) {
        num = 5;
    }

    static void foo(Boolean x){
            boolean y = false;
            x = y;
    }

it prints true and 9 btw.


Solution

  • Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing. Reference :https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

    What's the point of autoboxing primitives in Java?

    1. Could save you some time.

      int s=4; Integer s1=new Integer(s); //without autoboxing Integr s1=s; //autoboxing (saves time and some code) int k=s1; //unboxing

    Why Integer/Float/Decimal Objects? (using Integers to explain)

    1. An ArrayList of Integers/Floats/Doubles etc. as stated in Maroun's answer.

    2. Some inbuilt functions in Java Library returns Integer objects. So you could simply store the values in a primitive int using autoboxing instead of using returnedIntegerObject.intValue() .

    Let us convert String s="5" to integer.

    • Using the inbuilt function public static Integer valueOf(String s). As you can see the return type of this function is Integer and not int.

    Without Autoboxing:

    Integer a=Integer.valueOf(s);
    int b= a.intValue(); //getting the primitive int from Integer Object
    

    With Autoboxing

    int b=Integer.valueOf(s); //saves code and time