Autoboxing and Unboxing 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. If you are not yet familiar with the syntax of generics, see the Generics Updated lesson. Because li is a list of Integer objects, not a list of int values, you may wonder why the Java compiler does not issue a compile-time error.
|Published (Last):||22 December 2012|
|PDF File Size:||6.4 Mb|
|ePub File Size:||8.84 Mb|
|Price:||Free* [*Free Regsitration Required]|
Some context is required to fully understand the main reason behind this. Primitives versus classes Primitive variables in Java contain values an integer, a double-precision floating point binary number, etc.
Because these values may have different lengths , the variables containing them may also have different lengths consider float versus double. On the other hand, class variables contain references to instances. References are typically implemented as pointers or something very similar to pointers in many languages. These things typically have the same size, regardless of the sizes of the instances they refer to Object, String, Integer, etc. This property of class variables makes the references they contain interchangeable to an extent.
This allows us to do what we call substitution: broadly speaking, to use an instance of a particular type as an instance of another, related type use a String as an Object, for example. The most obvious reason for this but not the only reason is their size difference.
This makes primitive types inconvenient in this respect, but we still need them in the language for reasons that mainly boil down to performance. Generics and type erasure Generic types are types with one or more type parameters the exact number is called generic arity.
Generic types are a lot more complicated than non-generic ones. Generic arity and type parameter information are lost in this process, which is why we call it type erasure. The process of creating an Integer from an int, a Float from a float and so on, is called boxing. The reverse is called unboxing.
Autoboxing and Unboxing
Autoboxing und Autounboxing in Java
Autoboxing and Unboxing: