TYPE WRAPPERS
We will see how Java’s primitive types can be converted and considered objects. There are several reasons for having to make this conversion, and one of them is Generics. A Type Wrapper is a wrapper that we go and build around a primitive type. To be more precise, it is a class that encapsulates the primitive type.
Among the most important classes we can point out numerical types.
Classes are subclasses of Number. All numeric Wrapper classes have a special static method that takes the primitive type as a parameter and converts it to the corresponding Wrapper type. The method is called valueOf().
There is another particular form that takes a string as input.
BOXING AND UNBOXING
The mechanism we have seen at work, that is, taking as input a primitive value transformed into the corresponding Wrapper type is called Boxing. Let us see the reverse mechanism, that is, how to extract from a Wrapper type the corresponding primitive type. This mechanism is called Unboxing.
AUTO-BOXING AND AUTO-UNBOXING
Let’s see how to convert a primitive type to the corresponding Wrapper class and vice versa in a completely automatic way.
The conversion is done automatically. Autoboxing also occurs when we pass an argument to a method.
The same thing happens with return values. When possible always use primitive types since both Boxing and Unboxing always have a performance cost.
LINKS TO PREVIOUS POSTS
LINK TO CODE ON GITHUB
EXECUTION OF THE EXAMPLE CODE
- Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.
java -jar –enable-preview CorsoJava.jar
- Or run the main found in the file CorsoJava.java.
Leave A Comment