Skip Top Navigation Bar

Using Wrapper Classes

There are times when a reference type is preferred to a primitive type. In these cases, we can use wrapper classes. A wrapper class is a class that is used to create a reference object representation of a primitive value. In this tutorial, we will explore the following wrapper classes. You can find a list of all included methods in the Java documentation:

Creating Objects of Wrapper Classes

The wrapper classes have constructors; however, they are not necessary.

General Format:

<wrapper class name> variableName = <primitive value>;

Your Turn

Let's try this in the Java Playground.

Using Objects of Wrapper Classes

The compiler will implicitly convert between a primitive type and it's wrapper class equivalent. As such, you can perform arithemetic and boolean operators on these objects without having to explicitly convert between the types.

Your Turn

Let's try this in the Java Playground.

Converting from Reference Type to Primitive Type

To convert to a primitive type from a reference type, you simply need to assign the reference value to the corresponding primitive variable.

Your Turn

Let's try this in the Java Playground.

Integer Minimum and Maximum Values

The Integer class has two constants.

The range for int values are from Integer.MIN_VALUE to Integer.MAX_VALUE inclusive.

Your Turn

Let's try this in the Java Playground.

Wrapper Class Methods

The compiler automatically converts between the primitive types and their correspeonding object of the wrapper class, making the explicit use of the methods formly used to do these conversions unnecessary. There are a few methods that are incredibly helpful that we will call out in this tutorial.

Parsing Methods

The wrapper classes each have a method that can be used to return a representation of the String value as a primitive type.

Since these methods are static, we do not need to create an object to call them. They are called by using the class name.

Your Turn

Let's try this in the Java Playground.

In the Console Input and Output tutorial, we used the read and readln methods to obtain input from the user. When we use these methods, the type of input that is returned is String. What if you want to receive a different type of value as an input, such as an int, double, or boolean?

void main() {
    String input = readln("Enter your age: ");
    int age = Integer.parseInt(input);
    input = readln("Enter the average number of calories in a cookie: ");
    double avgCalories = Double.parseDouble(input);
    input = readln("Answer true or false. Do you like cookies?");
    boolean preferCookies = Boolean.parseBoolean(input);    
}

Resources

Next Learn Tutorial