1.9K
Table of Contents
In this article, you’ll learn about Wrapper class in Java, autoboxing, Unboxing, Features of Wrapper class and more
- Wrapper classes allow primitive data types to be accessed as objects and objects as a primitive data types.
- The various wrapper classes for primitive data type are: Boolean, Byte, Character, Double, Float, Integer, Long and Short.
- Wrapper classes make the primitive type data to act as objects.
Autoboxing
Autoboxing is the process of converting a primitive data type into corresponding wrapper class object. E.g. int to Integer.
Example: Sample program for autoboxing
class AutoBoxDemo
{
public static void main(String args[])
{
int x = 50;
Integer y = Integer.valueOf(x);
Integer z = x + y;
System.out.println(x+" "+y+" "+z);
}
}
Output
50 50 100
Unboxing
Converting an object of wrapper class into corresponding primitive data type is known as unboxing. For example Integer to int.
Example: Sample program for unboxing
class UnBoxDemo
{
public static void main(String args[])
{
Integer x = new Integer(15);
int y = x.intValue();
int z = x * y;
System.out.println(x+" "+y+" "+z);
}
}
Output
15 15 225
Primitive type and their corresponding wrapper class
Primitive type | Wrapper class |
---|---|
boolean | Boolean |
byte | Byte |
char | Character |
float | Float |
int | Integer |
long | Long |
short | Short |
double | Double |
Features of Wrapper class
- Wrapper classes convert numeric strings into numeric values.
- They provide a way to store primitive data into the object.
- The valueOf() method is available in all wrapper classes except Character.
- All wrapper classes have typeValue() method. This method returns the value of the object as its primitive type.
Character class method
- isDigit(): to determine whether the character is digit.
- isLower(): to determine whether the character is lower case alphabet.
- isLetter(): to determine whether the character is an alphabet.
Byte class method
- byteValue(): returns the Byte value as byte value.
- parseByte(): returns byte value from a byte string.
Integer class method
- intValue(): returns the Integer value as int value.
- parseInt(): returns the int value from a int string.