What is the Number Wrapper Class and its Methods in Java?


 

Introduction to `Number` Class in Java

In Java, the `Number` class is an abstract superclass of numeric wrapper classes. It serves as a base class for data types such as `Integer`, `Double`, `Float`, `Long`, `Short`, and `Byte`. The primary purpose of these wrapper classes is to provide a way to represent primitive data types as objects.

Sr.No Method & Description
1 byte byteValue() This method returns the value of the specified number as a byte.
2 abstract double doubleValue() This method returns the value of the specified number as a double.
3 abstract float floatValue() This method returns the value of the specified number as a float.
4 abstract int intValue() This method returns the value of the specified number as a int.
5 abstract long longValue() This method returns the value of the specified number as a long.
6 short shortValue() This method returns the value of the specified number as a short.

Common Methods of the `Number` Class

1. `intValue()`

This method returns the value of the `Number` object as an `int` primitive data type.

Integer numInt = new Integer(42);
int intValue = numInt.intValue();
System.out.println("Integer value: " + intValue);

2. `doubleValue()`

Similarly, `doubleValue()` returns the value of the `Number` object as a `double` primitive data type.

Double numDouble = new Double(3.14);
double doubleValue = numDouble.doubleValue();
System.out.println("Double value: " + doubleValue);

3. `floatValue()`

The `floatValue()` method returns the value of the `Number` object as a `float` primitive data type.

Float numFloat = new Float(2.718f);
float floatValue = numFloat.floatValue();
System.out.println("Float value: " + floatValue);

4. `longValue()`

This method retrieves the value of the `Number` object as a `long` primitive data type.

Long numLong = new Long(123456789);
long longValue = numLong.longValue();
System.out.println("Long value: " + longValue);

5. `byteValue()`

For integral types, the `byteValue()` method returns the value of the `Number` object as a `byte` primitive data type.

Byte numByte = new Byte((byte) 127);
byte byteValue = numByte.byteValue();
System.out.println("Byte value: " + byteValue);

Conclusion

The `Number` class and its subclasses provide a flexible way to work with numeric values in Java, allowing the use of primitive data types in an object-oriented context. These wrapper classes offer methods for converting numeric objects to their primitive counterparts, facilitating seamless integration between primitive types and their object representations.

       

Advertisements

ads