Wrapper Classes In Java
1. Introduction
The Java language supports both primitive and object types. However, some APIs such as the Collection API only accept object types. To allow primitive types to be used in such API, the language has defined Wrapper Classes. In this tutorial, you will learn the different types of wrapper classes in Java and how to use them.
2. Why Use a Wrapper class?
Here are common reasons why you might need to use a wrapper type:
- You use an API that only accepts object types (ex: Collection API)
- You want to convert from one primitive type to another
- You want to build a primitive type from a String object
There are three main categories of wrapper classes:
- Numeric wrapper classes: Byte, Short, Integer, Long, and Double
- Character wrapper class: Character
- Boolean wrapper class: Boolean
We will start by discussing the common features of all these wrapper classes. Afterwards, we will dig into specific features of each category.
3. Common Wrapper Class Utility Methods
One benefit of using Wrapper types is to have access to their utility methods.
3.1. Converting from Primitive Values to Wrapper Objects
There are two ways of achieving this: autoboxing and valueOf()
utility method.
3.1.1. Autoboxing
Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class. This happens whenever you provide a primitive value where an object is required.
Integer intObject = 1;//autoboxing is happening
Long longObject = 0L;
Double doubleObject = 1.0;
Character charObject = 'a';
Boolean booleanObject = false;
For all these five operations, autoboxing is happening behind the scenes.
valueOf()
method
3.1.2. Using the An alternative way of converting a primitive type to its wrapper class is by explicitly calling the valueOf
method. This approach might be preferable over autoboxing in some contexts, especially when caching is required.
Integer intObject = Integer.valueOf(1);
Long longObject = Long.valueOf(0L);
Double doubleObject = Double.valueOf(1.0);
Character charObject = Character.valueOf('a');
Boolean booleanObject = Boolean.valueOf(false);
3.2. Converting Strings to Wrapper Objects
Each wrapper type (except Character) defines a static method valueOf(String str)
that takes a string as an argument and returns the corresponding wrapper object. The method will throw a NumberFormatException if the string format is invalid for the required wrapper type.
Integer intObject = Integer.valueOf("1");//Cached
Long longObject = Long.valueOf("1000");//Not Cached
Double doubleObject = Double.valueOf("1.0");//Never cached
Boolean booleanObject = Boolean.valueOf("false");
These methods are useful in a context where you are reading raw data from a file (CSV) and need to store the values in Java objects.
For numeric wrapper classes (Byte, Short, Integer, Long, and Double), the method valueOf(String str)
will actually call another method parseXXXX(String str) behind the scenes. The only difference between the two methods is that the result of valueOf(String str)
is cached under certain circumstances.
Integer intObject2 = Integer.parseInt("1");//same as Integer.valueOf("1");
Long longObject2 = Long.parseLong("1000");//same as Long.valueOf("1000");
Double doubleObject2 = Double.parseDouble("1.0");//same as Double.valueOf("1.0");
Info: The result of the method
valueOf()
is always cached for integers within the range [-128, 127] for the wrapper classes Byte, Short, Integer, and Long.
3.3. Converting Wrapper objects to Strings
There are situations where you need to convert a wrapper type to a string, maybe because you need to save it to a file. To address that, each wrapper class overrides the toString()
method from the Object class and provides a convenient way to represent the primitive value in a text format.
String intStr = intObject.toString();
String longStr = longObject.toString();
String doubleStr = doubleObject.toString();
String booleanStr = booleanObject.toString();
3.4. Converting Primitive Values to Strings
Each wrapper class provides a static method toString(type t)
that takes a primitive value and converts it to its text representation.
String intStr = Integer.toString(1);
String longStr = Long.toString(0L);
String doubleStr = Double.toString(1.0);
String charStr = Character.toString('a');
String booleanStr = Boolean.toString(false);
3.5. Converting Wrapper objects to Primitive values
3.5.1. Unboxing
Unboxing is the reverse operation of autoboxing we saw earlier. It is the automatic conversion of a wrapper object to its corresponding primitive type.
int primitiveInt = intObject;//unboxing is happening
long primitiveLong = longObject;
double primitiveDouble = doubleObject;
char primitiveChar = charObject;
boolean primitiveBoolean = booleanObject;
For all these five operations, unboxing is happening behind the scenes.
typeValue()
method
3.5.2. Using the Alternatively, to unboxing, each wrapper class provides a method typeValue()
that returns the primitive value in the wrapper object.
int primitiveInt = intObject.intValue();
long primitiveLong = longObject.longValue();
double primitiveDouble = doubleObject.doubleValue();
char primitiveChar = charObject.charValue();
boolean primitiveBoolean = booleanObject.booleanValue();
Moreover, each wrapper class provides the typeValue()
method to convert its primitive value to any other primitive type.
int primitiveInt2 = longObject.intValue();//Narrowing: Potential loss of information
long primitiveInt3 = doubleObject.intValue();//Truncation: Potential loss of information
long primitiveLong2 = intObject.longValue();//Widening --> No loss of information
4. Numeric Wrapper classes
In addition to the features listed above, each numeric wrapper type defines a myriad of constants among which are the minimum and the maximum value possible for the corresponding primitive type.
Byte minByte = Byte.MIN_VALUE;
Byte maxByte = Byte.MAX_VALUE;
Short minShort = Short.MIN_VALUE;
Short maxShort = Short.MAX_VALUE;
int minInt = Integer.MIN_VALUE;
int maxInt = Integer.MAX_VALUE;
Long minLong = Long.MIN_VALUE;
Long maxLong = Long.MAX_VALUE;
Double minDouble = Double.MIN_VALUE;
Double maxDouble = Double.MAX_VALUE;
5. Character wrapper class
The Character class defines many useful static methods that can be used in any Java program dealing with characters. Some of the most used are:
-toLowerCase(char c)
-toUpperCase(char c)
-isLowerCase(char c)
-isUpperCase(char c)
-isDigit(char c)
-isLetter(char c)
char c1 = 'a';
char c2 = '1';
boolean isLowerCase = Character.isLowerCase(c1);//true
boolean isUpperCase = Character.isUpperCase(c1);//false
boolean isLetter = Character.isLetter(c1);//true
boolean isDigit = Character.isDigit(c2);//true
char c3 = Character.toUpperCase(c1);//A
The Character class also defines many constants among which you will find the minimum and the maximum value of the char type:
- Character.MIN_VALUE
- Character.MAX_VALUE
6. Boolean wrapper class
6.1. Boolean wrapper objects
Additionally, to the features we saw earlier in this article, the Boolean wrapper class also defines two wrapper objects to represent the boolean values true
and false
.
Boolean wrapperObjectTrue = Boolean.TRUE;
Boolean wrapperObjectFalse = Boolean.FALSE;
6.2. Converting Strings to Boolean values
The Boolean wrapper class defines a method parseBoolean(String str)
, which takes a string as the argument and returns true
if and only if the input string is equal to true
without considering the case.
Boolean stringToBoolean1 = Boolean.parseBoolean("true");//true
Boolean stringToBoolean2 = Boolean.parseBoolean("True");//true
Boolean stringToBoolean3 = Boolean.parseBoolean("false");//false
Boolean stringToBoolean4 = Boolean.parseBoolean("FALSE");//false
Boolean stringToBoolean5 = Boolean.parseBoolean("dummy string");//false
7. Conclusion
In this article, you have learned about the usefulness of wrapper classes in Java and how to use them in your applications.
You can find the complete code of this article here in GitHub.
Originally published at https://nkamphoa.com