TYPE WRAPPERS

java-logo

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.

Type wrapper

Among the most important classes we can point out numerical types.

Tipi numerici

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().

ValueOf

There is another particular form that takes a string as input.

String

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.

Estrazione tipo primitivo

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.

Autoboxing e auto-unboxing

The conversion is done automatically. Autoboxing also occurs when we pass an argument to a method.

Autoboxing nei metodi

The same thing happens with return values. When possible always use primitive types since both Boxing and Unboxing always have a performance cost.

Valori di ritorno e autoboxing

LINKS TO PREVIOUS POSTS

THE JAVA LANGUAGE

LINK TO CODE ON GITHUB

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.