Java Wrapper Classes
A wrapper class is a class that wraps a primitive value in an object. Integer wraps an int, and Double wraps a double.
Turn text into an int
parseInt reads the text 42 as the number 42. The sum then prints 50.
public class Main {
public static void main(String[] args) {
int value = Integer.parseInt("42");
System.out.println(value + 8);
}
}Turn text into a double
parseDouble reads the text 2.5 as the number 2.5. The product then prints 5.0.
public class Main {
public static void main(String[] args) {
double value = Double.parseDouble("2.5");
System.out.println(value * 2);
}
}Check a character
isLetter tests the character A and prints true. isDigit tests the same character and prints false.
public class Main {
public static void main(String[] args) {
System.out.println(Character.isLetter('A'));
System.out.println(Character.isDigit('A'));
System.out.println(Character.isDigit('7'));
}
}Box and unbox a value
The int value moves into an Integer object. The value then moves back into an int.
public class Main {
public static void main(String[] args) {
Integer score = 42;
int again = score;
System.out.println(score);
System.out.println(again + 8);
}
}Example
public class Main {
public static void main(String[] args) {
int quantity = Integer.parseInt("3");
double price = Double.parseDouble("4.5");
double total = quantity * price;
System.out.println(quantity);
System.out.println(price);
System.out.println(total);
}
}Key points
- Each primitive type has a matching wrapper class.
- Integer wraps int, Double wraps double, and Character wraps char.
- Integer.parseInt turns text into an int.
- Double.parseDouble turns text into a double.
- Character offers checks such as isLetter and isDigit.
- Autoboxing is the automatic conversion of a primitive into its wrapper object.
In this example, parseInt turns the text 3 into an int and parseDouble turns the text 4.5 into a double. The total line multiplies the two numbers. The prints show 3, 4.5, and the total 13.5.
Note
Wrapper classes appear in collections, because collections hold objects.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does Integer.parseInt("42") return?