Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Wrapper Classes

Java Wrapper Classes

Wrapper classes offer a means to utilize primitive data types (such as int, boolean, etc.) as objects.

The table below lists the primitive types alongside their corresponding wrapper classes:

Primitive Data Type

Wrapper Class

Byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

boolean

Boolean

char

Character

At times, wrapper classes are necessary, particularly when dealing with Collection objects like ArrayList, where primitive types cannot be employed directly, as the list can only accommodate objects.

Example

ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid

ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid

Creating Wrapper Objects

To instantiate a wrapper object, utilize the wrapper class instead of the primitive type. Retrieving the value can be achieved by simply printing the object.

Example

public class Main {
  public static void main(String[] args) {
    Integer myInt = 5;
    Double myDouble = 5.99;
    Character myChar = 'A';
    System.out.println(myInt);
    System.out.println(myDouble);
    System.out.println(myChar);
  }   
}

Now that you’re working with objects, you can employ specific methods to obtain information about the particular object.

For instance, you can utilize the following methods to retrieve the value associated with the respective wrapper object: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), and booleanValue().

This example will yield identical results to the one provided above:

Example

public class Main {
  public static void main(String[] args) {
    Integer myInt = 5;
    Double myDouble = 5.99;
    Character myChar = 'A';
    System.out.println(myInt.intValue());
    System.out.println(myDouble.doubleValue());
    System.out.println(myChar.charValue());
  }
}

Another valuable method is toString(), employed to convert wrapper objects into strings.

In the subsequent example, we convert an Integer to a String, then utilize the length() method of the String class to display the length of the resulting string.

Example

public class Main {
  public static void main(String[] args) {
    Integer myInt = 100;
    String myString = myInt.toString();
    System.out.println(myString.length());
  }
}