Skip to content

Java Numbers and Math Class

Java not only provides primitive data types (such as int, double) to handle numbers, but also offers a series of Wrapper Classes and a powerful Math class for more complex operations and calculations.

Number Wrapper Classes

For each primitive data type, Java provides a corresponding wrapper class. These classes "wrap" primitive types into objects, giving them more functionality, such as type conversion or participation in object-oriented operations (like storing in generic collections).

Primitive TypeWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Autoboxing and Unboxing

Starting from Java 5, Java introduced autoboxing and unboxing mechanisms, making the conversion between primitive types and wrapper classes seamless.

  • Autoboxing: Automatically converts a primitive type to its corresponding wrapper class object.
  • Unboxing: Automatically converts a wrapper class object to its corresponding primitive type.
java
// Autoboxing: int is automatically converted to Integer
Integer myIntObject = 100;

// Unboxing: Integer is automatically converted to int
int myIntPrimitive = myIntObject;

System.out.println(myIntObject.getClass().getName()); // Output: java.lang.Integer
System.out.println(myIntPrimitive); // Output: 100

Common Wrapper Class Methods

Wrapper classes provide many useful static and instance methods.

  • parseXXX(): Converts a string to the corresponding primitive type (e.g., Integer.parseInt("123")).
  • valueOf(): Converts a string or primitive type to the corresponding wrapper class object.
  • toString(): Converts a number to a string.
  • Comparison: equals() is used to compare whether the values of two objects are equal; compareTo() is used to compare the magnitude of two numbers.
java
public class WrapperClassExample {
    public static void main(String[] args) {
        // Use parseInt() to convert string to int
        String strNumber = "250";
        int number = Integer.parseInt(strNumber);
        System.out.println("Parsed integer: " + number);

        // Use valueOf() to get an Integer object
        Integer anotherNumber = Integer.valueOf("500");

        // Use compareTo() to compare values
        // Return value < 0: anotherNumber is less than 1000
        // Return value = 0: anotherNumber equals 1000
        // Return value > 0: anotherNumber is greater than 1000
        System.out.println(anotherNumber.compareTo(1000)); // Outputs negative number

        // Get Integer max and min value constants
        System.out.println("Integer max value: " + Integer.MAX_VALUE);
        System.out.println("Integer min value: " + Integer.MIN_VALUE);
    }
}

Math Class

The java.lang.Math class contains a series of static methods for performing basic mathematical operations, such as exponentials, logarithms, square roots, and trigonometric functions. You don't need to create an instance of the Math class; simply call its methods directly through the class name.

Common Math Methods

  • Math.abs(x): Returns the absolute value of x.
  • Math.max(a, b): Returns the larger of a and b.
  • Math.min(a, b): Returns the smaller of a and b.
  • Math.sqrt(x): Returns the positive square root of x.
  • Math.pow(a, b): Returns a raised to the power of b (a^b).
  • Math.round(x): Returns the rounded long or int value of x.
  • Math.ceil(x): Returns the smallest integer greater than or equal to x (ceiling).
  • Math.floor(x): Returns the largest integer less than or equal to x (floor).
  • Math.random(): Returns a random double value in the range [0.0, 1.0).

Trigonometric Functions

  • Math.sin(a), Math.cos(a), Math.tan(a): The parameter a is an angle in radians.
  • Math.toDegrees(rad): Converts radians to degrees.
  • Math.toRadians(deg): Converts degrees to radians.

Example:

java
public class MathExample {
    public static void main(String[] args) {
        double x = 25.0;
        double y = -10.5;

        System.out.println("Square root of 25 is: " + Math.sqrt(x)); // 5.0
        System.out.println("2 to the power of 8 is: " + Math.pow(2, 8)); // 256.0
        System.out.println("Absolute value of -10.5 is: " + Math.abs(y)); // 10.5
        System.out.println("Ceiling of 4.3: " + Math.ceil(4.3)); // 5.0
        System.out.println("Floor of 4.7: " + Math.floor(4.7)); // 4.0
        System.out.println("Rounding 4.5: " + Math.round(4.5)); // 5

        // Generate a random integer between 1 and 10
        int randomNumber = (int)(Math.random() * 10) + 1;
        System.out.println("Random number 1-10: " + randomNumber);

        // Calculate the sine of 90 degrees
        double angleInDegrees = 90.0;
        double angleInRadians = Math.toRadians(angleInDegrees);
        System.out.println("sin(90 degrees) = " + Math.sin(angleInRadians)); // 1.0
    }
}

Content is for learning and research only.