-1

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.

shinzou
  • 5,850
  • 10
  • 60
  • 124
  • 3
    Java is *pass by value*, always, with no exceptions. You're changing the reference inside the method, which won't affect the original passed value. Also recall that `Integer` is *immutable*. – Maroun Aug 21 '16 at 14:12
  • But isn't `num = 5;` considered unboxing? So it changes the value inside the object and the ref to this object is the same. @MarounMaroun – shinzou Aug 21 '16 at 14:19

2 Answers2

1

The point of having these wrapper classes is mostly for generics. In Java, if I wanted to make an ArrayList of integers, I CANNOT do the following:

ArrayList<int> intList = new ArrayList<int>()

This will not work, since generics only work for objects, and an "int" is a primitive. By using the wrapper,

ArrayList<Integer> intList = new ArrayList<Integer>()

I can fix this problem.

Maroun
  • 94,125
  • 30
  • 188
  • 241
John
  • 2,575
  • 1
  • 17
  • 29
1

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
Mathews Mathai
  • 1,707
  • 13
  • 31