Question

This question is about "Why does autoboxing make some calls ambiguous in Java?"

But reading through the answers, there are a number of references to casting and I'm not sure I completely understand the difference.

Can someone provide a simple explanation?

Was it helpful?

Solution

Boxing is when you convert a primitive type to a reference type, un-boxing is the reverse. Casting is when you want one type to be treated as another type, between primitive types and reference types this means an implicit or explicit boxing operation. Whether it needs to be explicit is a language feature.

OTHER TIPS

Both casting and boxing/unboxing have to do with types and apparent (or real) conversion, but boxing/unboxing is specific to the relationship between primitive types and their corresponding wrapper types, while casting is the term for explicit or implicit change of type in the more general sense.

Casting is a general term with two related-but-different meanings:

  1. Treating a value of one type as if it were a value of another type. Two examples of this first usages are:

    1.1. Given that class B extends class A, you can ask for myB an instance of B to be treated as an instance of A by writing ((A) myB) wherever a reference to an instance of A could appear. This doesn't actually produce a new instance of A.

    1.2. Pre-Java5 collections stored all content as Object; this usually required you to use a cast after retrieving an object from a collection. For example, if you had stored a String in a Map and needed to get its length, you'd write something like ((String) myMap.get(someKey)).length() where the cast would be required in order to call the length method of String. Again, this doesn't cause a new String to be created.

  2. Explicitly converting one type to another (i.e. explicitly changing the representation). An example of this second usage is in the expression ((int) (float_var + 0.5F)) which rounds a floating-point variable by adding 0.5 (which produces a floating-point value) and then explicitly converting that value to an integer. The resulting integer value (after the (int) cast) is produced from the other value by internal computation.

Casting can be done when there's a superclass/subclass or interface/implementor relationship (meaning 1 above) or when the two types are primitive numeric types (meaning 2). You might look up "widening" and "narrowing" for more detail.

Boxing refers to wrapping primitive types in container objects, usually only done when you must have an object (e.g. storing a value in a collection). The primitive and wrapper types come in pairs:

int      Integer
long     Long
boolean  Boolean
...      ...

Unboxing simply means retrieving the primitive value from within its object wrapper.

As of Java5, when you write an expression that uses a primitive value where the corresponding wrapper type would be required (such as putting an integer into a collection), the compiler automagically slips in the code that actually wraps that primitive value. Likewise it will provide the unwrapping code for you.

So instead of writing (in pre-Java5) something like:

Map myMap = new HashMap();
...
myMap.put(someKey,Integer.valueOf(3));
...
int nextValue = (myMap.get(someKey)).intValue() + 1;

you can write:

Map<KeyType,Integer> myMap = new HashMap<KeyType,Integer>();
...
myMap.put(someKey,3);
...
int nextValue = myMap.get(someKey) + 1;

and the boxing/unboxing code is inserted by the compiler.

List<String> list = (List<String>)object;

is a cast.

void doSomething(Integer i) { ... }
...
doSomeething(5);

is auto-boxing.

Integer getSomething();
...
int i = getSomething();

is auto-unboxing.

Autoboxing was introduced in Java 5 to prevent code such as :

map.put("ABC", new Integer(5));
map.put("DEF", new Integer(6));

You can now say :

map.put("ABC", 5);

Whilst its easier - it does have a few pitfalls if you aren't completely sure of what you are doing.

Boxing is wrapping a value inside a container, such as an int primitive value inside an Integer object

Casting is just how to look at the type.

The former produces another kind of value, the later just modifies how to treat an already existing value

Except casting between primitive types actually modifies their representation. (This doesn't make it clearer does it?)

Boxing and unboxing is a type of cast in Java, where you cast from a primitive to its wrapper class or the inverse, e.g. boolean to Boolean (box), or Boolean to boolean (unbox).

Types of casts in Java, with example:

  • an identity conversion (§5.1.1) String to String

  • a widening primitive conversion (§5.1.2) byte to int

  • a narrowing primitive conversion (§5.1.3) int to byte

  • a widening reference conversion (§5.1.5) Integer to Number

  • a narrowing reference conversion (§5.1.6) Number to Integer

  • a boxing conversion (§5.1.7) int to Integer

  • an unboxing conversion (§5.1.8). Integer to int

Autoboxing or autounboxing happens when the compiler does the boxing/unboxing conversion for you (it doesn't explicitly appear in the source code as a cast expression), e.g. see the question you referred to.

Does Autoboxing and Unboxing can be applied in the following case ?

Long one = 10;
long two = 15;
Long three = 20;

if(one == three) //will this be unboxed or do we need to put a explicit
                 //condition like if(one.intValue() == three.intValue()) 
   System.out.println("Equal");
else 
   System.out.println("Not Equal");  


if(one == two) //will this be unboxed or do we need to put a explicit
               //condition like if(one.intValue() == two) 
   System.out.println("Equal");
else 
   System.out.println("Not Equal");  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top