Java Wrapper Classes - Working with Primitive Types as Objects

Understand Java wrapper classes, which enable the use of primitive data types (like int, boolean) as objects. Explore how to convert between primitive types and wrapper classes for enhanced functionality in Java.



Java Wrapper Classes

Wrapper classes allow you to use primitive data types (like int, boolean, etc.) as objects. Here are the primitive types and 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

Sometimes you need to use wrapper classes, especially when working with collections like ArrayList, which can only store objects, not primitive types:

Syntax

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

Creating Wrapper Objects

To create a wrapper object, use the wrapper class instead of the primitive type. You can then access the value and use methods specific to that object:

Syntax

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);
}
}

Output

Output

5
5.99
A

Using Methods of Wrapper Objects

You can use methods like intValue(), doubleValue(), charValue(), etc., to get the value associated with the wrapper object:

Syntax

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());
}
}

Using the toString() Method

The toString() method converts wrapper objects to strings. For example, convert an Integer to a String and find its length:

Syntax

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