Java Math Class: Comprehensive Guide to Numeric Operations
Explore the Java Math class in-depth, including its powerful methods for performing essential numeric operations such as exponentials, logarithms, square roots, and trigonometric functions. Learn how to use the java.lang.Math class effectively in your Java programs.
Java Numbers Class
Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc.
Example:
int i = 5000;
float gpa = 13.65f;
double mask = 125;
Sometimes, we need to use objects instead of primitive data types. To achieve this, Java provides wrapper classes. All wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number
.
Java Number Class
The Number
class is an abstract class in the java.lang
package. It is the superclass of classes that represent numeric values convertible to primitive data types such as byte, short, int, long, float, and double.
Converting primitive data types into objects is called boxing, and the compiler handles this automatically. Unboxing is the process of converting the wrapper object back to a primitive data type. The Number
class is part of the java.lang
package.
Example of Boxing and Unboxing
This example shows how to use primitives and their operations using a wrapper class. In the first statement, an int is assigned to an Integer object x
(boxing). In the second statement, 10 is added to x
(unboxing), and the result is printed.
public class Test {
public static void main(String args[]) {
Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to an int
System.out.println(x);
}
}
15
When x
is assigned an integer value, the compiler boxes the integer because x
is an Integer object. Later, x
is unboxed so it can be added as an integer.
Java Number Class Methods
Here are some methods all subclasses of the Number
class implement:
Method | Description |
---|---|
byteValue() |
Returns the value as a byte. |
doubleValue() |
Returns the value as a double. |
floatValue() |
Returns the value as a float. |
intValue() |
Returns the value as an int. |
longValue() |
Returns the value as a long. |
compareTo() |
Compares this Number object to another. |
equals() |
Checks if this Number object is equal to another. |
valueOf() |
Returns an Integer object holding a specified value. |
toString() |
Returns a String object representing the value. |
parseInt() |
Converts a String to an int. |
min() |
Returns the smaller of two values. |
max() |
Returns the larger of two values. |
Java Number: Wrapper Classes
Wrapper classes for primitive types:
Class | Description |
---|---|
Boolean |
Wraps a boolean value. |
Byte |
Wraps a byte value. |
Character |
Wraps a char value. |
Double |
Wraps a double value. |
Float |
Wraps a float value. |
Integer |
Wraps an int value. |
Long |
Wraps a long value. |
Short |
Wraps a short value. |