-1

hi all i am still beginner to java may someone explain to me what is the difference between auto-boxing and Un-boxing use for and when to use that?

          //this is my sample code

     ArrayList<Double> listOfDoubles = new ArrayList<Double>();
     for(double i = 0.0; i <= 10.0; i += 0.5) {
      listOfDoubles.add(Double.valueOf(i)); // this why we could use double value of?
     }
Steven Y.
  • 41
  • 1
  • 6
  • Have you read https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html yet? – VGR Jul 23 '18 at 14:26

2 Answers2

0

For doubles, Autoboxing means implicitly (without a cast nor anything that shows off we're doing it) converting a double value, the primitive type, to a Double value, the corresponding object type.

Auto unboxing is the opposite: implicitly converting a Double value to a double value.

You use it when you want to convert a primitive to an object, or an object to a primitive. Typically when wanting to store double values in a List, well, Lists cannot store primitives but they can store objects, so you can convert the doubles to Doubles, and store them in Lists. Without explicitly saying in the program, "hey, my double here, make it a Double before you store it somewhere that can take in Doubles!"

listOfDoubles.add(Double.valueOf(i)); // this why we could use double value of?

You can because why not. It's completely unneeded to call Double.valueOf(i) as the compiler will do that implicitly if you hadn't done it explicitly.

Unneeded, but not forbidden. Notably, autoboxing and unboxing were introduced with Java 1.5. It didn't exist before. So, before, you needed a way to box and unbox your values when you needed to. Double.valueOf() is such a way.

It wouldn't make sense to suddenly forbid it and break older programs that used it, just because it's not needed anymore in modern Java.

kumesana
  • 2,495
  • 1
  • 9
  • 10
0

unboxing is converting an object type primitive value (or boxed type) into it's primitive counterpart (Integer to int, Double to double).

Auto-boxing means that a primitive can be converted automatically into a boxed or object type.

int i = 4;
Integer j = i;

variable j is an Integer object type that contains value 4.

Be careful with unboxing as null objects cannot be transformed into primitive values.

Martín Zaragoza
  • 1,717
  • 8
  • 19