Java Number Class Tutorial

In Java, the Number class is an abstract superclass for all numeric wrapper classes such as Integer, Double, Float, Long, Short, and Byte.

These wrapper classes convert primitive data types into objects and provide several useful methods to manipulate numeric values.

The Number class is part of the java.lang package and provides methods for converting numbers between different types, such as int, float, double, etc.

It also provides methods for comparing, parsing, and converting numbers from one form to another.

In this tutorial, we'll cover:

1. Introduction to the Number Class and Wrapper Classes

The Number class is an abstract class that provides a foundation for all the wrapper classes of the numeric primitive data types:

Integer: Wrapper class for the primitive int.
Double: Wrapper class for the primitive double.
Float: Wrapper class for the primitive float.
Long: Wrapper class for the primitive long.
Short: Wrapper class for the primitive short.
Byte: Wrapper class for the primitive byte.
These classes inherit the Number class and offer methods to convert between various number types.

2. Methods of the Number Class

The Number class provides several abstract methods that are implemented by its subclasses. These methods allow you to convert a number from one type to another:

intValue(): Returns the value of the number as an int.
longValue(): Returns the value of the number as a long.
floatValue(): Returns the value of the number as a float.
doubleValue(): Returns the value of the number as a double.
shortValue(): Returns the value of the number as a short.
byteValue(): Returns the value of the number as a byte.
These methods are useful when you want to convert a number from one type to another without explicit casting.

Example 1: Using Number Methods to Convert Between Types

public class NumberMethodsExample {
    public static void main(String[] args) {
        Integer intObj = 100;
        Double doubleObj = 123.45;

        // Converting Integer to other types
        System.out.println("Integer as int: " + intObj.intValue());
        System.out.println("Integer as long: " + intObj.longValue());
        System.out.println("Integer as double: " + intObj.doubleValue());

        // Converting Double to other types
        System.out.println("Double as int: " + doubleObj.intValue());
        System.out.println("Double as float: " + doubleObj.floatValue());
        System.out.println("Double as long: " + doubleObj.longValue());
    }
}

Explanation:

intValue(), longValue(), and doubleValue() are used to convert the Integer and Double objects to different numeric types.

3. Working with Numeric Wrapper Classes

Java provides wrapper classes that allow you to work with primitive numeric types as objects. These wrapper classes provide methods to perform operations like converting strings to numbers, parsing, comparing numbers, and more.

Example 2: Using Wrapper Classes

public class WrapperClassExample {
    public static void main(String[] args) {
        // Creating wrapper objects from primitive types
        Integer intObj = Integer.valueOf(10);
        Double doubleObj = Double.valueOf(25.75);
        Float floatObj = Float.valueOf(15.5f);

        // Accessing the primitive values from wrapper objects
        int intValue = intObj.intValue();
        double doubleValue = doubleObj.doubleValue();
        float floatValue = floatObj.floatValue();

        System.out.println("Integer value: " + intValue);
        System.out.println("Double value: " + doubleValue);
        System.out.println("Float value: " + floatValue);
    }
}

Explanation:

Integer.valueOf(), Double.valueOf(), and Float.valueOf() create wrapper objects from primitive values.
intValue(), doubleValue(), and floatValue() return the primitive values stored in the wrapper objects.

4. Converting Numbers Between Types

The Number class provides several methods to convert one numeric type to another, such as from Integer to Double, or from Double to Float.

Example 3: Converting Numeric Types

public class NumberConversionExample {
    public static void main(String[] args) {
        Integer intObj = 50;
        Double doubleObj = 99.99;

        // Convert Integer to Double and Long
        Double convertedDouble = intObj.doubleValue();
        Long convertedLong = intObj.longValue();

        System.out.println("Integer converted to Double: " + convertedDouble);
        System.out.println("Integer converted to Long: " + convertedLong);

        // Convert Double to Integer and Float
        Integer convertedInteger = doubleObj.intValue();
        Float convertedFloat = doubleObj.floatValue();

        System.out.println("Double converted to Integer: " + convertedInteger);
        System.out.println("Double converted to Float: " + convertedFloat);
    }
}

Explanation:

Converting Integer to Double: The intObj.doubleValue() method converts the integer value to a Double.
Converting Double to Integer: The doubleObj.intValue() method converts the Double to an Integer.

5. Parsing Strings to Numbers

The numeric wrapper classes (Integer, Double, Float, etc.) provide static methods like parseInt(), parseDouble(), and parseFloat() to convert strings to numbers.

Example 4: Parsing Strings to Numbers

public class ParseNumberExample {
    public static void main(String[] args) {
        String intStr = "100";
        String doubleStr = "99.99";

        // Parsing strings into numeric values
        int intValue = Integer.parseInt(intStr);
        double doubleValue = Double.parseDouble(doubleStr);

        System.out.println("Parsed integer: " + intValue);
        System.out.println("Parsed double: " + doubleValue);

        // Handling invalid number format
        try {
            String invalidNumber = "abc";
            int invalidInt = Integer.parseInt(invalidNumber);  // This will throw NumberFormatException
        } catch (NumberFormatException e) {
            System.out.println("Invalid number format: " + e.getMessage());
        }
    }
}

Explanation:

Integer.parseInt() converts a string to an integer.
Double.parseDouble() converts a string to a double.
NumberFormatException is thrown if the string cannot be converted into a number (e.g., trying to parse “abc” as an integer).

6. Comparing Numbers

Wrapper classes like Integer, Double, and Float implement the Comparable interface, allowing them to be compared using the compareTo() method.

Example 5: Comparing Numbers

public class CompareNumbersExample {
    public static void main(String[] args) {
        Integer num1 = 10;
        Integer num2 = 20;
        Integer num3 = 10;

        // Comparing numbers using compareTo()
        System.out.println("Comparing num1 and num2: " + num1.compareTo(num2));  // Output: -1
        System.out.println("Comparing num2 and num1: " + num2.compareTo(num1));  // Output: 1
        System.out.println("Comparing num1 and num3: " + num1.compareTo(num3));  // Output: 0

        // Using equals() method
        System.out.println("Is num1 equal to num2? " + num1.equals(num2));  // Output: false
        System.out.println("Is num1 equal to num3? " + num1.equals(num3));  // Output: true
    }
}

Explanation:

compareTo() returns:
0 if both numbers are equal.
A negative value if the first number is smaller than the second.
A positive value if the first number is larger than the second.
equals() checks whether two numbers are equal.

7. Auto-Boxing and Unboxing

Java automatically converts between primitive types and their corresponding wrapper classes. This process is called auto-boxing (converting primitives to objects) and unboxing (converting objects to primitives).

Example 6: Auto-Boxing and Unboxing

public class AutoBoxingUnboxingExample {
    public static void main(String[] args) {
        // Auto-boxing: primitive to object
        Integer intObj = 50;  // Equivalent to Integer.valueOf(50)

        // Unboxing: object to primitive
        int intValue = intObj;  // Equivalent to intObj.intValue()

        System.out.println("Auto-boxed Integer: " + intObj);
        System.out.println("Unboxed int: " + intValue);
    }
}

Explanation:

Auto-boxing: Java automatically converts the primitive 50 to an Integer object.
Unboxing: Java automatically converts the Integer object back to a primitive int.

8. Key Considerations

Precision Loss: When converting from floating-point types (float or double) to integer types (int, long), the fractional part will be lost.
Exceptions: Be aware of NumberFormatException when parsing strings into numbers, especially when the input string is not a valid numeric value.
Auto-boxing/Unboxing: Java handles most conversions between primitive types and wrapper classes automatically, but be mindful of performance when dealing with large datasets.

Conclusion

In this tutorial, we explored the Number class in Java and how it serves as a superclass for wrapper classes like Integer, Double, Float, Long, Short, and Byte. We covered:

Methods of the Number class for converting numbers between types.
Working with wrapper classes for numeric types.
Parsing strings into numbers using methods like parseInt() and parseDouble().
Comparing numbers using compareTo() and equals().
Auto-boxing and unboxing for seamless conversion between primitives and wrapper objects.

Understanding the Number class and its subclasses is essential when working with numbers in Java, whether it's for parsing input, performing arithmetic, or comparing values.

Related posts

Java Data Types Tutorial

Java Boolean Class Tutorial

Java User Input Tutorial