|
All methods of the Math class are public and static. They can be accessed like any static method by using the class name. Usually these methods return some value. The following sections describe the important methods in Math class with code examples showing how to use them.
The abs() method returns the absolute value of the argument. Theoretically, the absolute value of a number is how far it is from zero. In simple words, the absolute value of any number (say number a) is the number itself, if the number is positive or zero, and − a , if a is negative. For example,
int a1 = Math.abs(32); // Value of a1 is 32
int a2 = Math.abs(-32) // Value of a2 is 32
The method is overloaded to take an int, long, float, or double argument. The signatures of the abs()method are as follows:
public static int abs(int a)
public static long abs(long a)
public static float abs(float a)
public static double abs(double a)
The value returned by these methods has the exact same type as the argument passed. For instance, if abs() is called by passing a double argument, result is also a double value.
|
|
If a value of data type that is narrower that int (such as byte or short) is passed, it is automatically converted to int and the abs() method that takes int argument is invoked. |
The max() method takes two numeric arguments and returns the greater of the two. For example,
int biggerOne = Math.max(7, 11); // result is 11
The Math class has four overloaded versions of this method to handle int, long, float, or double type of arguments. The signatures of the max() method are as follows:
public static int max(int a, int b)
public static long max(long a, long b)
public static float max(float a, float b)
public static double max(double a, double b)
If the both arguments a and b are of equal value then max() returns their value as a result. The type of result is always decided based on which of the above four versions is invoked. For instance, in the following code, the result is of type float due to promotions.
long no1 = 4;
float no2 = 4.3f;
float result = max(no1, no2);
|
|
The methods of Math class are simple. However while answering question in exam, be extra careful with whether their return type is correct and whether they are assigned to a variable of appropriate type. To make sure, you must be able to know which version of method will be invoked for the given set of arguments. In chapter 10 (Conversion and casting), we learned how the data types are promoted during the method calls. The same principal applies when, say for instance, you call the max() method with a long and a float value. Now, there is no max()method that accepts (long, float) but there is one that accepts both float arguments. Therefore, the long argument will be promoted to float and max(float, float) version will be invoked. Therefore, the type of returned value will be float. |
The min() method works opposite to the max()method. It takes two numeric arguments and returns the smaller of the two. For example,
double smallerOne = Math.min(-4.2, 1.7); // smallerOne is –4.2
The Math class has four overloaded versions of this method to handle int, long, float, or double arguments. The signatures of the min() method are as follows:
public static int min(int a, int b)
public static long min(long a, long b)
public static float min(float a, float b)
public static double min(double a, double b)
Similar to the max() method, if the both arguments, a and b of min() are of equal value then it returns that value as a result. The type of the result is decided based on which of the above four versions is invoked.
The random() method returns a random value of type double that is greater than or equal to 0.0 but which is less than 1.0. For instance if d is the value returned by random() then d is always (0 <= d < 1.0). The random() method does not take any argument. The signature of the random() method is as follows:
public static double random()
There are two important things to remember about random() method,
It returns a value of double type.
It returns a value in the range of 0.0 to 1.0. It can return 0.0 but it never returns 1.0.
You can create random numbers in the other range by multiplying the double value returned by random(). For example, if you want to print ten whole numbers between 1 to 25 randomly, you can do so by multiplying the value returned by random() with 25 as:
System.out.print("Ten random numbers between 1 to 25 are ...");
for (int i = 0; i < 10; i++) {
System.out.print((int)(Math.random()* 25) + " " );
}
When you multiply the result of Math.random()by 25, you get a double value between 0.0 and 24.99999999999999 (and up to the precision allowed by the type double). Since you need the whole numbers, you can cast this double value to an int. The result might look like this.
Ten random numbers between 1 to 25 are ...17 13 20 14 5 18 16 21 2 16
Note that the result can be different each time you run the code because random() generates values randomly.
|
|
In the exam, you could be given a code and asked which of the values could be part of output. While answering this type of question, remember that random() never returns 1.0. For Therefore, in the recent example, the number 25 can never be the part of the output. |
The sqrt() method returns the square root of its argument. The signature of the sqrt()method is as follows:
public static double sqrt(double a)
Since the argument is of double type, you can pass any narrower primitive type. This method will return its square root as a value of double type. In the following example, Math.sqrt(16) returns double value 4.0.
System.out.println("Square root of 16 is " + Math.sqrt(16));
Mathematically, you can find the square root of a negative numbers as well. The result is a complex number comprised of real and imaginary parts. But the Java Math.sqrt() method returns Double.NaN instead of a complex number. NaN is a bit pattern that denotes that the value it represents is “not a number”. This bit pattern is defined in wrapper classes for float and double primitives. We will see more about NaN in wrapper classes.
The Math class has only one ceil() method and it has the following signature:
public static double ceil(double a)
The ceil() method accepts an argument of type double and returns a double value. It performs a ceiling operation on its argument. Mathematically, the ceiling function of a number x is the smallest integer, which is not smaller than x. In simple words, if you pass a fractional number as argument, the ceiling function will round it to the nearest integer of equal or more value. For example, all of the following statement assigns a double value 5.
double result1 = Math.ceil(4.15); // result1 is 5.0
double result2 = Math.ceil(4.5); // result2 is 5.0
double result3 = Math.ceil(4.8); // result3 is 5.0
double result4 = Math.ceil(5.0); // result4 is 5.0
The ceiling operation is a bit confusing about negative numbers. The logic is still same. You only need to remember that in case of negative numbers a number with bigger magnitude is actually smaller. For instance, -5 is less than –4. All the following statements show the ceiling of negative values.
double result1 = Math.ceil(-4.15); // result1 is -4.0
double result2 = Math.ceil(-4.5); // result2 is -4.0
double result3 = Math.ceil(-4.8); // result3 is -4.0
double result4 = Math.ceil(-5.0); // result4 is -5.0
Thus ceiling is always towards the nearest greater integer value. Figure 13.2 illustrates the ceiling operation with the help of approximate number scale.
![]() |
Figure 13.2 Ceiling is always to the nearest bigger integer
Figure shows how ceiling always returns the closest integer to the right hand side of the number. The important thing to note is that the result of ceil() is a integer which is represented as double value. Therefore Math.ceil(-4.15) is a double value -4.0 (and not int value -4) .
Another operation related to number rounding is the flooring. The Math class has only one floor() method and it has the following signature.
public static double floor(double a)
Theoretically, the floor of a number x is the largest integer that is not larger than x. The floor method works exactly opposite of the ceil method. The ceil() method gives you the nearest bigger (upper) integer whereas the floor() method gives the nearest smaller integer. For instance, all the following statements show the flooring of values:
double result1 = Math.floor(4.15); // result1 is 4.0
double result2 = Math.floor(4.5); // result2 is 4.0
double result3 = Math.floor(4.8); // result3 is 4.0
double result4 = Math.floor(5.0); // result4 is 5.0
The flooring operation of negative numbers follows the same logic. But remember that in case of negative numbers, a number with bigger magnitude is actually smaller. For instance, -5 is less than –4. All the following statements assigns the double value -5.0:
double result1 = Math.floor(-4.15); // result1 is -5.0
double result2 = Math.floor(-4.5); // result2 is -5.0
double result3 = Math.floor(-4.8); // result3 is –5.0
double result4 = Math.floor(-5.0); // result4 is -5.0
Figure 13.3 illustrates the flooring operation with a approximate number scale.
![]() |
Figure 13.3 Flooring is always to the nearest smaller integer
Figure shows how flooring always returns the closest integer to the left hand side of the number. The important thing to note is that the result of floor() is a integer which is represented as double value. Therefore Math.floor(-4.15) is a double value -5.0 (and not int value -5) .
Simple rule of thumb for ceil and floor
The ceiling and flooring functions work just like the ceiling and flooring of the house. Remember you have to go up towards greater numbers while doing the ceil operation and down towards smaller numbers while doing the floor operation. Figure 13.4 illustrates the analogy with an approximate number scale and a house metaphor.
![]() |
Figure 13.4 ceil() and floor() methods analogy with the ceiling and flooring of a home
The third and last operation related with number rounding is the actual round operation. The Math class has two overloaded versions of round() method. They have the following signatures.
public static int round(float a)
public static long round(double a)
The round() method accepts an argument either of type float or double and returns either a int or long value respectively. This method does rounding in a conventional sense. It returns the integer that is closest to the argument. The round() method finds the nearest integer by following the next three steps.
Adds 0.5 to the argument.
Floors the result of this addition.
Casts the result of flooring to the appropriate return type (either int or long).
Figure 13.5 illustrates these three steps to find Math.round(4.5).

Figure 13.5 Steps to find out the result of invoking Math.round() on a positive floating-point number
Figure illustrates the three steps. First 0.5 is added to the argument. Secondly, the result is floored. Finally, the result is cast to either an int or long value depending on argument. The argument 4.5 is of type double. Hence the result is of type long. The rounding of floating-point numbers of type float is exactly same except the returned result is an int value. You can predict the result using the same logic as figure 13.5. All of the following statement illustrates rounding of positive float values to nearest integer values.
int result1 = Math.round(4.15f); // result1 is 4
int result2 = Math.round(4.5f); // result2 is 5
int result3 = Math.round(4.8f); // result3 is 5
Remember that when you can also pass an argument of double type to the round() method, the round() returns a long value. The rest of the logic is same.
Rounding of negative numbers
The logic for predicting the result of rounding of negative numbers is exactly same as figure 13.5. Here also you need to follow the three steps:
1. Add 0.5 to the argument.
2. Floor the result of this addition.
3. Cast the result of flooring to the appropriate return type (either int or long).
![]() |
Figure 13.6 Steps to find out the result of invoking Math.round() on a negative number
Note that when you add 0.5 to a -4.5, the result is -4. The result of flooring -4.0 is -4.0. Hence -4.5 is rounded to int value -4.
Let us take another example.
In Math.round(-4.15), first 0.5
added to the argument. The result would be -3.7. Then you can floor the result to get -4.0
(not -3.0). This result is
then cast to a long value to get -4L. All of the following statement
illustrates the rounding of negative floating-point numbers of type double.
long result2 = Math.round(-4.2); // result2 is -4L
long result2 = Math.round(-4.5); // result2 is -4L
long result2 = Math.round(-4.7); // result2 is -5L
|
|
Keep in mind that rounding of negative numbers can cause confusion. For instance, Math.round(-4.5) is -4L, but Math.round(4.5) is 5L. The key point to remember is that unlike positive numbers, a negative number with larger magnitude is actually smaller. For instance, -4.5 is smaller than -4. |
The sin() method is one of the methods offering the trigonometric functions in Math class. It returns the trigonometric sine of an angle.
|
|
Theoretically, a trigonometric function is a function whose argument is an angle, and whose value is some ratio of side lengths in a right-angled triangle that has that angle in it. |
The signature of the sin() method is as follows:
public static double sin(double a)
This method takes the angle as an argument of double type. This angle is assumed to be in radians (Radians is a unit of measuring angles in trigonometry). For example, you can get sine of angle of 0 radians (0r) as:
System.out.println("Sine of 0 radians " + Math.sin(0));
If you wish to pass the angle in degrees, you need first convert the degrees into radians before invoking the sine method. For instance, an angle of 90 degrees (900) can be converted to radians by calling the Math.toRadians() method.
System.out.println("Sine of 90 degrees " + Math.sin(Math.toRadians(90)));
Since the sin(90) is 1, the Math.sin(Math.toRadians(90) returns a double value 1.0.
The cos() method is returns the cosine of an angle. The signature of the cos() method is as follows:
public static double cos(double a)
This method takes the angle as an argument of double type and returns a double value. This angle is also assumed to be in radians. For example, you can get cosine of angle of 0 radians (0r) as:
System.out.println("Cosine of 0 radians " + Math.cos(0));
The tan() method is returns the tangent of an angle. The signature of the tan() method is as follows:
public static double tan(double a)
This method also takes the angle as an argument of double type and returns a double value. This angle is assumed to be in radians. For example, you can get the tangent of an angle of 0 radians (0r) as:
System.out.println("Tangent of 0 radians " + Math.tan(0));
The toDegrees() method takes an angle in radians and returns the equivalent angle in degrees. The signature of the toDegrees() method is as follows:
public static double toDegrees(double a)
This method accepts the angle in radians as a double value and returns the angle in degrees also as a double value.
|
|
There is a relationship between the radians and PI. PI is commonly used to represent the ratio of the circumference of a circle to its diameter. Radians is the unit of angle chosen so that the number of radians in a full circle is exactly twice the value of PI (which approx 22/7). In other words, 3600 is equivalent to 2*PI radians. This relation is useful to simplify the formulas for calculating the area of a sector in a circle etc. |
For example, if we pass an angle in radians that is equivalent to twice the value of PI, we get 360 degrees as:
System.out.println("Angle of 2*PI radians is equivalent to " + Math.toDegrees(Math.PI * 2.0)); // 360 degrees
The toRadians() method takes an argument representing an angle in degrees and returns the equivalent angle in radians. The signature of the toRadians() method is as follows:
public static double toRadians(double a)
The angle in radians is accepted as double value and the angle in degrees is returned as a double value. For example, if we pass an angle in 360 degrees the value returned is an angle in radians that is equivalent to twice the value of PI.
System.out.println("Angle of 2*PI radians is equivalent to " +
Math.toRadians(360.0)); // 6.283185, which is aprrox. equal to 2*Math.PI
This method is very useful for converting an angle in degrees into an argument suitable for use with the trigonometric methods. As we have seen earlier, the trigonometric methods such as sin() method expects angle in radians. toRadians() is useful when you know the angle in degrees and wants to find out a trigonometric function of it. For example, to determine the sin of 180 degrees, you can use toRadians() as:
double angleInRad = Math.toRadians(180);
System.out.println("sin(180) = " + Math.sin(angleInRad) );
Thus the toRadians() method is also useful for converting an angle in degrees into an angle in radians with other trigonometric methods cos(), tan() as well as the methods for arc functions acos(), asin() and atan()).
Summary of methods in java.lang.Math class
The table 13.1 summarizes all the important static methods of Math class along with their signatures and a brief description.
Table 13.1 Important methods of java.lang.Math class.
|
Method signature |
Brief Description |
|
public static int abs(int a) public static long abs(long a) public static float abs(float a) public static double abs(double a) |
Returns the absolute value of argument.
|
|
public static int max(int a, int b) public static long max(long a, long b) public static float max(float a, float b) public static double max(double a, double b) |
Returns the greater number of the two arguments |
|
public static int min(int a, int b) public static long min(long a, long b) public static float min(float a, float b) public static double min(double a, double b) |
Returns the smaller number of the two arguments |
|
public static double random() |
Returns random number d such that- 0.0 <= d < 1.0 |
|
public static double sqrt(double a) |
Returns the correctly rounded positive square root of argument. If argument is negative then it returns a double value NaN. |
|
public static double ceil(double a) |
Returns the smallest integer (as a double value), which is not smaller than argument. |
|
public static double floor(double a) |
Returns the largest integer (as a double value), which is not larger than argument. |
|
public static int round(float a) public static long round(double a) |
Returns the integer that is closest to the argument. |
|
public static double sin(double a) |
Returns the trigonometric sine of an argument (angle in radians). |
|
public static double cos(double a) |
Returns the trigonometric cosine of an argument (angle in radians).. |
|
public static double tan(double a) |
Returns the trigonometric tangent of an argument (angle in radians).. |
|
public static double toRadians(double angdeg) |
Returns angle in radians for angle passed in degrees. |
|
public static double toDegrees(double angrad) |
Returns angle in degrees for angle passed in radians. |