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
Each wrapper class has two constructors: one requires String as an argument and the other constructor requires the value of the corresponding data types as an argument. Each of these classes has the following methods:
doubleValue
(returns the value a double)floatValue
(returns the value a float)intValue
(returns the value an integer)longValue
(returns the value a long)shortValue
(returns the value a short)byteValue
(returns the value 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 creates a new instance from the Strings:
Integer intObject = Integer.valueOf("19");
It is also possible to create a value of primitive data type from String using the corresponding parsing methods:
double arvdouble4 = Double.parseDouble("21");
Session 4 |