Autoboxing in Java and rules for wrapping primitive types in wrapper classes

Autoboxing is a mechanism for implicitly initializing objects of wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, Boolean) with the values ​​of their corresponding original primitive types (byte, short, int ...), without explicitly using the class constructor.

  • Autoboxing occurs when the primitive is directly assigned to the wrapper class (using the = operator), or when the primitive is passed to the method parameters (of the wrapper class type).
  • Both primitive variables and compile-time constants (literals and final primitives) can be autoboxed into wrapper classes. In this case, literals must be syntactically correct to initialize a variable of the original primitive type.
  • Autoboxing of variables of primitive types requires an exact match of the type of the original primitive to the type of the wrapper class. For example, an attempt to package a variable of type byte into Short without first explicitly casting byte into short will cause a compilation error.
  • Autoboxing of constants of primitive types allows wider matching boundaries. In this case, the compiler is able to preliminarily perform implicit expansion/contraction of the primitive type:
    • implicit expansion/contraction of the original primitive type to the primitive type corresponding to the wrapper class (for converting int to Byte, first the compiler implicitly narrows int to byte itself)
    • autoboxing the primitive into the appropriate wrapper class. However, in this case, there are two additional restrictions: a) the assignment of the primitive to the wrapper can only be performed using the = operator (such a primitive cannot be passed to the method parameters without explicit type casting) b) the type of the left operand must not be older than Character, the type of the right one must not be older than int: expansion/contraction of byte to/from short, byte to/from char, short to/from char and only narrowing byte from int, short from int, char from int is allowed. All other options require explicit casting).

An additional feature of integer wrapper classes created by autoboxing constants in the -128 ... +127 range is that they are cached by the JVM. Therefore, such wrappers with the same values ​​will be references to one object.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed