Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrappers and Auto-boxing

There is the following code:

Integer time = 12;
Double lateTime = 12.30;
Boolean late = false;
Double result = late ? lateTime : time;  //Why here can I assign an Integer to a Double?
System.out.println(result);

It prints:

12.0

This one doesn't compile. Why?

Integer time = 12;
Double lateTime = 12.30;
Double result = time;      //Integer cannot be converted to Double
System.out.println(result);
like image 841
Davide Avatar asked Jan 23 '17 10:01

Davide


People also ask

What does Autoboxing mean?

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.

What is type wrapper What is the role of Autoboxing?

Autoboxing is the automatic conversion of the primitive types into their corresponding wrapper class. For example, converting an int to an Integer , a char to a Character , and so on. We can simply pass or assign a primitive type to an argument or reference accepting wrapper class type.

What is the difference between boxing and Autoboxing?

Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you. For instance, if you write in code: // list is a List<Integer> list.

What are wrapper types?

A Wrapper class is a class which contains the primitive data types (int, char, short, byte, etc). In other words, wrapper classes provide a way to use primitive data types (int, char, short, byte, etc) as objects. These wrapper classes come under java. util package.


1 Answers

The differences are due to the ternary operator behaviour in Java.


The ternary conditional case:

In the expression late ? lateTime : time, Java will auto-unbox exactly one of the arguments (according to the value of late) to its respective primitive type. (You can observe this by setting time to null and late to true: a NullPointerException is not thrown. The same applies when setting lastTime to null and late to false.)

If the value of the expression will be time, then this is widened to a double.

In either case, the resulting double is auto-boxed to a Double in assigning it to result.


The simple assignment case:

In writing Double result = time;, Java disallows this as it expects you to be more explicit.


Personally I find the mechanism of the Java ternary conditional operator with respect to the boxed primitive types to be one of the most pernicious parts of the language.

like image 74
Bathsheba Avatar answered Sep 22 '22 15:09

Bathsheba