17.8: Wrapper Classes
- Page ID
Primitive values (like
chars) do not provide methods. For example, you can’t call
equals on an
int i = 5; System.out.println(i.equals(5)); // compiler error
But for each primitive type, there is a corresponding class in the Java library, called a wrapper class. The wrapper class for
char is called
int it’s called
Integer. Other wrapper classes include
Double. They are in the
java.lang package, so you can use them without importing them.
Each wrapper class defines constants
MAX_VALUE. For example,
2147483647. Because these constants are available in wrapper classes, you don’t have to remember them, and you don’t have to include them in your programs.
Wrapper classes provide methods for converting strings to other types. For example,
Integer.parseInt converts a string to (you guessed it) an integer:
String str = "12345"; int num = Integer.parseInt(str);
In this context, parse means something like “read and translate”.
The other wrapper classes provide similar methods, like
Boolean.parseBoolean. They also provide
toString, which returns a string representation of a value:
int num = 12345; String str = Integer.toString(num);
The result is the string