Java Number Class Methods with Examples

The Number class is part of the java.lang package and serves as the superclass for classes representing numeric values, such as Byte, Double, Float, Integer, Long, and Short. The Number class is abstract, meaning it cannot be instantiated directly. Instead, it provides a common interface for converting numeric values to various primitive types.

The Number class defines the following methods, which are inherited and implemented by its subclasses:

  1. byteValue()
  2. shortValue()
  3. intValue()
  4. longValue()
  5. floatValue()
  6. doubleValue()

Methods of the Number Class

1. byteValue()

Returns the value of the specified number as a byte.

Example:

public class NumberExample {
    public static void main(String[] args) {
        Integer num = 100;
        byte byteValue = num.byteValue();
        System.out.println("Byte value: " + byteValue);
    }
}

Output:

Byte value: 100

2. shortValue()

Returns the value of the specified number as a short.

Example:

public class NumberExample {
    public static void main(String[] args) {
        Integer num = 100;
        short shortValue = num.shortValue();
        System.out.println("Short value: " + shortValue);
    }
}

Output:

Short value: 100

3. intValue()

Returns the value of the specified number as an int.

Example:

public class NumberExample {
    public static void main(String[] args) {
        Double num = 100.5;
        int intValue = num.intValue();
        System.out.println("Int value: " + intValue);
    }
}

Output:

Int value: 100

4. longValue()

Returns the value of the specified number as a long.

Example:

public class NumberExample {
    public static void main(String[] args) {
        Float num = 100.5f;
        long longValue = num.longValue();
        System.out.println("Long value: " + longValue);
    }
}

Output:

Long value: 100

5. floatValue()

Returns the value of the specified number as a float.

Example:

public class NumberExample {
    public static void main(String[] args) {
        Long num = 100L;
        float floatValue = num.floatValue();
        System.out.println("Float value: " + floatValue);
    }
}

Output:

Float value: 100.0

6. doubleValue()

Returns the value of the specified number as a double.

Example:

public class NumberExample {
    public static void main(String[] args) {
        Short num = 100;
        double doubleValue = num.doubleValue();
        System.out.println("Double value: " + doubleValue);
    }
}

Output:

Double value: 100.0

Conclusion

The Number class provides a set of methods for converting numeric values to different primitive types. These methods are implemented by the subclasses of Number, including Byte, Double, Float, Integer, Long, and Short. By using these methods, you can easily convert between different numeric types, ensuring that your code can handle various numeric representations effectively.

Comments