Session 4 |
Wrapper class
In Java, there are eight primitive data types: byte
, short
, integer
, long
, float
, double
, char
and boolean
. Unfortunately, not all methods want to operate on primitive data types, but want to get objects as an argument. Hence, we need to convert a primitive data type into an object.
Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes because they wrap the primitive data type into an object of that class.
Useful link: Check the fields, constructors and methods of each wrapper class: Byte, Short, Integer, Long, Float, Double, Char and Boolean
Wrapper classes of numbers have two constructors: one requires a String type object as an argument and another constructor requires a value of the corresponding data type as an argument. Each of these classes has one of the following methods:
doubleValue
(returns the value of this Double object as a double)floatValue
(returns the value of this Float object as a float)intValue
(returns the value of this Integer object as an int)longValue
(returns the value of this Long object as a long)shortValue
(returns the value of this Short object as a short)byteValue
(returns the value of this Byte object as a byte)
The wrapper classes which operate on numbers also have constants MAX_VALUE
and MIN_VALUE
which hold the values of the minimum and maximum of the corresponding type. See examples:
System.out.println(Double.MIN_VALUE); System.out.println(Byte.MAX_VALUE); System.out.println(Integer.MAX_VALUE);
Also these wrapper classes have a static method valueOf
which returns a new object of the specified String object:
Integer intObject = Integer.valueOf("19");
It is also possible to create a value of primitive data type from a String object using the corresponding parsing methods, e.g.:
double numDouble4 = Double.parseDouble("21");
Session 4 |