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).
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.
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.
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 ofx.Math.max(a, b): Returns the larger ofaandb.Math.min(a, b): Returns the smaller ofaandb.Math.sqrt(x): Returns the positive square root ofx.Math.pow(a, b): Returnsaraised to the power ofb(a^b).Math.round(x): Returns the roundedlongorintvalue ofx.Math.ceil(x): Returns the smallest integer greater than or equal tox(ceiling).Math.floor(x): Returns the largest integer less than or equal tox(floor).Math.random(): Returns a randomdoublevalue in the range[0.0, 1.0).
Trigonometric Functions
Math.sin(a),Math.cos(a),Math.tan(a): The parameterais an angle in radians.Math.toDegrees(rad): Converts radians to degrees.Math.toRadians(deg): Converts degrees to radians.
Example: