Number Class

The Number class is a wrapper class in Java that encapsulates primitive numeric types such as byte, short, int, long, float, and double as objects. It provides a number of useful methods to perform various operations on numeric values. Here are some common methods of the Number class:

  1. byteValue(): Returns the value of the Number object as a byte.

  2. shortValue(): Returns the value of the Number object as a short.

  3. intValue(): Returns the value of the Number object as an int.

  4. longValue(): Returns the value of the Number object as a long.

  5. floatValue(): Returns the value of the Number object as a float.

  6. doubleValue(): Returns the value of the Number object as a double.

  7. equals(Object obj): Compares the Number object with the specified object for equality.

  8. toString(): Returns a string representation of the Number object.

  9. hashCode(): Returns the hash code value for the Number object.

  10. compareTo(Number anotherNumber): Compares the Number object with another Number object.

  11. isNaN(): Returns true if the value of the Number object is NaN (not a number).

  12. isInfinite(): Returns true if the value of the Number object is infinite.

Example use the Number class in Java

refer to‮:‬theitroad.com
public class NumberExample {
    public static void main(String[] args) {
        // Create a Number object
        Number num = 123.45;
        System.out.println("Number is: " + num);

        // Convert the Number object to an integer
        int intValue = num.intValue();
        System.out.println("Integer value is: " + intValue);

        // Convert the Number object to a double
        double doubleValue = num.doubleValue();
        System.out.println("Double value is: " + doubleValue);

        // Check if the Number object is an instance of a particular class
        boolean isInstance = num instanceof Double;
        System.out.println("Is instance of Double? " + isInstance);
    }
}