Number Class
Normally, when we work with numbers, we use primitive data types such as byte
, int
, long
, double
, etc.:
int i = 5000;
float gpa = 13.65;
double mask = 0xaf;
|
|
|
However, in development, we come across situations where we need to use objects instead of primitive data types.
In order to achieve this, Java provides wrapper classes.
All the wrapper classes (Integer
, Long
, Byte
, Double
, Float
, Short
) are subclasses of the abstract class Number
, which is part of the java.lang
package.
The object of the wrapper class contains or wraps its respective primitive data type.
- Boxing:
It converts a primitive data type into an object, and it is taken care by the compiler.
Therefore, while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the wrapper class.
- Unboxing:
It converts the wrapper object back to a primitive data type.
The following is an example of boxing and unboxing:
public class Test {
public static void main( String args[ ] ) {
Integer x = 5; // Boxes int to an Integer object.
x = x + 10; // Unboxes the Integer to an int.
System.out.println( x ); // Output: 15
}
}
|
When
x
is assigned an integer value, the compiler boxes the integer because
x
is an Integer object.
Later,
x
is unboxed so that it can be added as an integer.
MyPrime.java (checking whether a number is prime)
|
|
|
What did the pirate say when he turned 80?
Aye Matey.
|