Math Class in Java | Methods, Example

Java programming supports the basic mathematical computation through the class Math defined in java.lang package.

The java.lang.Math class contains two constants and a collection of methods that we can use to perform basic mathematical operations.

The common mathematical operations may be square root, cube root, elementary exponential, logarithm, trigonometrical functions, etc.

Java Math Class declaration


Java language added math class in JDK 1.0. The general declaration of Math class is as:

public final class Math
extends Object

The class java.lang.Math extends Object class. Since the class is final, so we cannot extend it. The constructor of Math class is private, so we cannot create an instance of this class.

Fortunately, all the constants and methods defined in Math class are static, so they are class variables and class methods.

We can access them through the class name. We do not need to create an instance of Math class.

The general syntax to call any method or constant defined in the Math class is:

Math.function_name(arguments);
For example,
  Math.sqrt(2);

How to Import Math class in Java?


Math class has been defined in java.lang package. It has the various math functions. We can import Math class using the following syntax:

import java.lang.Math;

To make our lives easier, Java compiler automatically imports java.lang.Math class in every application.

Constants defined in Java Math class


The java.lang.Math class contains two constants that are as:

1. static double E: This constant represents the value of e, the base of the natural logarithms.

2. static double PI: This constant represents the value of pi, the ratio of the circumference of a circle to its diameter. PI is  a frequently used Math class constant.

Both constants defined in the Math class are public, static, final, and double.

Note the following points:

  • public, so any program can access it directly.
  • final, so it cannot be changed.
  • static, so only one copy will exist and we can access it using class name without constructing Math object.
  • double, so it stores a floating-point value.

Let’s create a Java program to calculate the area of a circle. In this example, we will call the constant PI of Math class.

Program code 1:

package javaProgram;
public class Circle {
public static void main(String[] args) 
{	
 int radius = 2;
 double areaOfCircle = Math.PI * radius * radius;
 System.out.println("Area of circle = " +areaOfCircle);
 }
}
Output:
      Area of circle = 12.566370614359172

Methods defined by Math class in Java


In addition to constants, java.lang.Math class provides many useful methods. For example, Math.max() method returns larger of two numbers and Math.abs() method returns the absolute value of a number.

Let’s understand all the mathematical methods with definitions and syntaxes defined by Java Math class one by one with examples.

1. abs(x): This method returns the Absolute value of the specified value by ignoring sign. The general syntax is:

public static int abs(int i)
public static double abs(double d)
public static float abs(float f)
public static long abs(long l)

The abs() method returns the absolute value of the argument.

  • If we provide positive or negative value as an argument, the result will be positive value.
  • If the argument is infinity, the result will be positive infinity.
  • This method will return NaN if the argument is NaN.

Note that if the argument is equal to the Integer.MIN_VALUE value or Long.MIN_VALUE value, the most negative representable int value or long value, the result is that same value, which is negative.

Find absolute value of a number


Let’s create a Java program to find the absolute value of some numeric value.

Program code 1:

public class AbsExample {
public static void main(String[] args) 
{
   int x = 20, y = -10;  
// Displaying the absolute value of int type value.  
   System.out.println("Math.abs(x): " +Math.abs(x));  
   System.out.println("Math.abs(y): " +Math.abs(y));  
   System.out.println("Math.abs(Integer.Min_VALUE): " +Math.abs(Integer.MIN_VALUE)); 	
  
   double p = -27.83, q = -999.37;  
// Displaying the absolute value of double type value.  
   System.out.println("Math.abs(p): " +Math.abs(p));  
   System.out.println("Math.abs(q): " +Math.abs(q));  
   System.out.println("Math.abs(10/0): " +Math.abs(10.0 / 0)); 
 }
}
Output:
      Math.abs(x): 20
      Math.abs(y): 10
      Math.abs(Integer.Min_VALUE): -2147483648
      Math.abs(p): 27.83
      Math.abs(q): 999.37
      Math.abs(10/0): Infinity

2. max(x, y): This method returns the largest of given two argument values. The general syntax of this method is:

public static int max(int x, int y)
public static long max(long x, long y)
public static double max(double x, double y)
public static float max(float x, float y)

In the above syntax, x and y are the two arguments.

Find the largest number of two numbers in Java


Let us write a program to find the largest of given two numbers in Java.

Program code 2:

public class MaxExample {
public static void main(String[] args) 
{
   int x = 20, y = 50;  
// Displaying the maximum of two numbers.   
   System.out.println("Math.max(20, 50): " +Math.max(x, y));  
 
   double p = 25.25, q = -25.589 ;
   System.out.println("Math.max(25.25, -25.589): " +Math.max(p, q));
   float a = -10.10f, b = -20.20f;
   System.out.println("Math.max(-10.10f, -20.20f): " +Math.max(a, b));
 }
}
Output:
      Math.max(20, 50): 50
      Math.max(25.25, -25.589): 25.25
      Math.max(-10.10f, -20.20f): -10.1

As you can see in the output, if we provide positive and negative value as argument, the method returns positive argument. But, if we provide both negative values as argument, the method returns the lower magnitude value.


3. min(x, y): This method returns the smallest out of given two arguments. The general syntax of this method is:

public static int min(int x, int y)
public static long min(long x, long y)
public static float min(float x, float y)
public static double min(double x, double y)

In the above syntax, x and y are the two arguments.

Find the smallest number of two numbers in Java


Let us write a program to find the smallest number of given two numbers in Java.

Program code 3:

public class MinExample {
public static void main(String[] args) 
{
 int x = 10, y = 20;  
// Displaying the minimum of two numbers.   
   System.out.println("Math.min(10, 20): " +Math.min(x, y));  
 double p = 25.25, q = -25.589 ;
 System.out.println("Math.min(25.25, -25.589): " +Math.min(p, q));
 float a = -10.10f, b = -20.20f;
 System.out.println("Math.min(-10.10f, -20.20f): " +Math.min(a, b));
 }
}
Output:
      Math.min(10, 20): 10
      Math.min(25.25, -25.589): -25.589
      Math.min(-10.10f, -20.20f): -20.2

4. round(x): This method adds 0.5 to the argument and returns the nearest integer value, if the fractional part is greater than or equal to 0.5. The general syntax is:

public static int round(float x)
public static long round(double x)

Here, x is a floating-point value to be rounded to an integer. The round() method returns the value of the argument rounded to the closest integer value.

Rounding float and double values to integer


Let’s write a program to round float and double numbers to integer value in Java using Math.round() method.

Program code 4:

public class RoundExample {
public static void main(String[] args) 
{
 double x = 10.08, y = -20.60;  
// Displaying the rounding of two numbers.   
  System.out.println("Math.round(10.08): " +Math.round(x));  
  System.out.println("Math.round(-20.06): " +Math.round(y));
 }
}
Output:
      Math.round(10.08): 10
      Math.round(-20.06): -21

5. sqrt(x): This method returns the square root of a specified positive number. The general syntax is:

public static double sqrt(double x)

Here, x is the number to be found the square root.

Finding the square root of a number in Java


Let us write a Java program to find the square root of a positive number using Math.sqrt() method.

Program code 5:

public class SquareRroot {
public static void main(String[] args) 
{
   double x = 16, y = 20.60;  
// Displaying the square root of two numbers.   
   System.out.println("Math.sqrt(16): " +Math.sqrt(x));  
   System.out.println("Math.sqrt(20.60): " +Math.sqrt(y));
 }
}
Output:
      Math.sqrt(16): 4.0
      Math.sqrt(20.60): 4.538722287164087

6. cbrt(x): This method returns the cube root of a specified positive number.The general syntax of this method is:

public static double cbrt(double x)

Here, x is the number to be found the cube root.

Find the cube root of a number in Java


Let’s write a Java program to find the cube root of a positive number using Math.cbrt() method.

Program code 6:

public class CubeRoot {
public static void main(String[] args) 
{
  double x = 64, y = 1000.64;  
// Displaying the cube root of two numbers.   
  System.out.println("Math.cbrt(64): " +Math.cbrt(x));  
  System.out.println("Math.cbrt(1000.64): " +Math.cbrt(y));
 }
}
Output:
      Math.cbrt(64): 4.0
      Math.cbrt(1000.64): 10.002132878383971

7. pow(x, y): This method is used to find the power of any numeric data. That is, it returns the value of first argument raised to the power to second argument. The general syntax of this method is:

public static double pow(double x, double x)

Here, x and y are the values of xy.

Find the power of xy


Let’s create a Java program to find the power of 42 and 16.00.5.

Program code 7:

public class Power {
public static void main(String[] args) 
{
   double x = 4, y = 2;  
// Displaying the power of numeric data.   
  System.out.println("Math.pow(4,2): " +Math.pow(x, y));
  
  double a = 16.0, b = 0.5;
  System.out.println("Math.pow(16.0, 0.5): " +Math.pow(a, b));
 }
}
Output:
      Math.pow(4,2): 16.0
      Math.pow(16.0, 0.5): 4.0

8. signum(x): This method is used to find the sign of a specified value. The general syntax is:

public static double signum(double x)
public static float signum(float x)

Here, x is a floating-point value whose signum is to be returned. The signum() function returns the following values:

  • If the argument is = 0, this method returns zero.
  • If the argument is > 0, returns 1.0f.
  • If the argument is < 0, returns -1.0f.

Find the sign of a number


Let’s create a Java program to find the sign of a given number using signum() function.

Program code 8:

public class SignumExample {
public static void main(String[] args) 
{
 double x = -25.6;
 float y = 0.0f;
 double z = 0.0/0;
 System.out.println(Math.signum(x));  
 System.out.println(Math.signum(y));
 System.out.println(Math.signum(z));
 }
}
Output:
       -1.0
        0.0
        NaN

9. ceil(x): This method is used to find the smallest integer value not less than x (ceiling). The general signature of this method is:

public static double ceil(double x)

Here, x is the number to be found the ceiling. The ceil() method returns numerically equivalent to the next higher integer value.

Find the ceiling value of a number in Java


Let us write a Java program to find the ceiling value of a specified number using Math.ceil() method.

Program code 9:

public class CeilExample {
public static void main(String[] args) 
{
 System.out.println("Math.ceil(61.3): " +Math.ceil(61.3));  
 System.out.println("Math.ceil(-61.3): " +Math.ceil(-61.3));
 System.out.println("Math.ceil(100): " +Math.ceil(100));
 System.out.println("Math.ceil(10.1): " +Math.ceil(10.1));
 
 System.out.println("Math.ceil(55.5): " +Math.ceil(55.5));
 System.out.println("Math.ceil(-200): " +Math.ceil(-200));
 System.out.println("Math.ceil(0): " +Math.ceil(0));
 }
}
Output:
      Math.ceil(61.3): 62.0
      Math.ceil(-61.3): -61.0
      Math.ceil(100): 100.0
      Math.ceil(10.1): 11.0
      Math.ceil(55.5): 56.0
      Math.ceil(-200): -200.0
      Math.ceil(0): 0.0

10. floor(x): This method is used to find the largest integer value not greater than x. The general signature of this method is:

public static double floor(double x)

Here, x is the number to be found the flooring. The floor() method returns numerically equivalent to the next lower integer value.

Find the flooring value of a number in Java


Let’s make a Java program to find the floor of a specified number using Math.floor() method.

Program code 10:

public class FloorExample {
public static void main(String[] args) 
{
 System.out.println("Math.floor(61.3): " +Math.floor(61.3));  
 System.out.println("Math.floor(-61.3): " +Math.floor(-61.3));
 System.out.println("Math.floor(100): " +Math.floor(100));
 System.out.println("Math.floor(10.1): " +Math.floor(10.1));
 
 System.out.println("Math.floor(55.5): " +Math.floor(55.5));
 System.out.println("Math.floor(-200): " +Math.floor(-200));
 System.out.println("Math.floor(0): " +Math.floor(0));
 }
}
Output:
      Math.floor(61.3): 61.0
      Math.floor(-61.3): -62.0
      Math.floor(100): 100.0
      Math.floor(10.1): 10.0
      Math.floor(55.5): 55.0
      Math.floor(-200): -200.0
      Math.floor(0): 0.0

11. random(): This method returns any random number between 0.0 and 1.0. It does not accept any argument value. The general syntax of this method is:

public static double random( )

Find the random value between 0 to 1


Let’s create a Java program to find the random number between 0 to 1.

Program code 11:

package javaProgram;
public class RandomNumberEx {
public static void main(String[] args) 
{
// Generate any random number between 0 to 1.  
   double x = Math.random();  
   double y = Math.random();  
// Output may be different every time when this code will execute.    
    System.out.println(x);  
    System.out.println(y);
 }
}
Output:
      0.013146118533061801
      0.4956644103170965

12. rint(x): This method returns the rounded off value of x. In other word, the rint() method returns the nearest integer to x. The general syntax is:

public static double rint(double x)

Here, x is the double value to be rounded off to the nearest mathematical integer.

Find the rounded off value of numeric data


Let’s take an example program to find the rounded off value of numeric data.

Program code 12:

public class RoundedOffEx {
public static void main(String[] args) 
{
 double x = 25.68, y = -34.56, z = 89.40;
 System.out.println("Math.rint(x): " +Math.rint(x));
 System.out.println("Math.rint(y): " +Math.rint(y));
 System.out.println("Math.rint(z): " +Math.rint(z));
 }
}
Output:
      Math.rint(x): 26.0
      Math.rint(y): -35.0
      Math.rint(z): 89.0

13. addExact(x, y): This method returns the sum of its argument values. The general syntax to use this method is:

public static int addExact(int x, int y)
public static long addExact(long x, long y)

The addExact() method will throw an exception if the result overflows either int or long. Let’s take an example based on this method.

Program code 13:

public class Addition {
public static void main(String[] args) 
{
 int x = 25, y = 30;
 System.out.println("Math.addExact(x, y): " +Math.addExact(x, y));
 long a = 30, b = -80;
 System.out.println("Math.addExact(a, b): " +Math.addExact(a, b));
 }
}
Output:
      Math.addExact(x, y): 55
      Math.addExact(a, b): -50

14. subtractExact(x, y): This method returns the difference of the argument values. The general syntax to use this method is:

public static int subtractExact(int x, int y)

The subtractExact() method will throw an exception if the result overflows an int. Let’s take an example for this method.

Program code 14:

public class Subtraction {
public static void main(String[] args) 
{
 int x = 25, y = 30;
 System.out.println("Math.subtractExact(x, y): " +Math.subtractExact(x, y));
 long a = 30, b = -80;
 System.out.println("Math.subtractExact(a, b): " +Math.subtractExact(a, b));
 }
}
Output:
     Math.subtractExact(x, y): -5
     Math.subtractExact(a, b): 110

15. multiplyExact(x, y): This method returns the product of the arguments. The general syntax to use this method is:

public static int multiplyExact(int x, int y)
public static long multiplyExact(long x, long y)

The multiplyExact() method will throw an exception if the result overflows an int or long. Let’s take an example on this method.

Program code 15:

public class Multiplication {
public static void main(String[] args) 
{
 int x = 25, y = 30;
 System.out.println("Math.multiplyExact(x, y): " +Math.multiplyExact(x, y));
 long a = 30, b = -80;
 System.out.println("Math.multiplyExact(a, b): " +Math.multiplyExact(a, b));
 }
}
Output:
      Math.multiplyExact(x, y): 750
      Math.multiplyExact(a, b): -2400

16. incrementExact(x): This method returns the argument incremented by one, throwing an exception if the result overflows either an int or long.

public static int incrementExact (int x)
public static long incrementExact (long x)

Program code 16:

public class Incrementation {
public static void main(String[] args) 
{
 int x = 25;
 System.out.println("Math.incrementExact(x): " +Math.incrementExact(x));
 long a = -80;
 System.out.println("Math.incrementExact(a): " +Math.incrementExact(a));
 }
}
Output:
     Math.incrementExact(x): 26
     Math.incrementExact(a): -79

17. decrementExact(x): This method returns the argument decremented by one, throwing an exception if the result overflows an int or long. The general syntax is as:

public static int decrementExact(int x)
public static long decrementExact(long x)

18. negateExact(x): This method returns the negation of an argument, throwing an exception if the result overflows an int or long. The overflow only occurs for the minimum value. The general syntax is:

public static int negateExact (int x)
public static long negateExact (long x)

Let’s take an example program where we will find the negation of a number.

Program code 17:

public class Negation {
public static void main(String[] args) 
{
 int x = 25;
 System.out.println("Math.negateExact(x): " +Math.negateExact(x));
 long a = -80;
 System.out.println("Math.negateExact(a): " +Math.negateExact(a));
 }
}
Output:
      Math.negateExact(x): -25
      Math.negateExact(a): 80

Most Important Logarithmic Math class Methods


1. log(x): This method finds out the logarithmic value of any numeric data. It returns the natural logarithm (base e) of a double value as a parameter. The general signature of this method is:

public static double log(double x)

Here, x is a value to be found logarithmic value.

Find the Logarithmic value of a number in Java


Let’s create a Java program to find the logarithmic value of a number using Math.log() method.

Program code 1:

public class LogExample {
public static void main(String[] args) 
{
 int x = 625;
 System.out.println("Math.log(x): " +Math.log(x));
 long a = -80;
 System.out.println("Math.log(a): " +Math.log(a));
 }
}
Output:
      Math.log(x): 6.437751649736401
      Math.log(a): NaN

2. log10(x): This method finds out the Logarithmic of a number when the base is 10. It returns the base 10 logarithm of a double value. The general signature of this method is:

public static double log10(double x)

Let’s take an example program on this method.

Program code 2:

public class AbsExample {
public static void main(String[] args) 
{
 int x = 625;
 System.out.println("Math.log10(x): " +Math.log10(x));
 long a = -80;
 System.out.println("Math.log10(a): " +Math.log10(a));
 }
}
Output:
      Math.log10(x): 2.7958800173440754
      Math.log10(a): NaN

3. exp(x): This method returns E raised to the power of a double value, where E is Euler’s number and it is approximately equal to 2.71828. The general method definition is:

public static double exp(double x)

Here, x is the exponent value which raises to e. The exp() method returns the value ex, where e is the base of the natural logarithms.

Find the exponential of a number in Java


Let’s create a Java program to find out the exponential of a number using Math.exp() method.

Program code 3:

public class ExponentialExample {
public static void main(String[] args) 
{
 int x = 25;
 System.out.println("Math.exp(x): " +Math.exp(x));
 long a = -8;
 System.out.println("Math.exp(a): " +Math.exp(a));
 }
}
Output:
      Math.exp(x): 7.200489933738588E10
      Math.exp(a): 3.3546262790251185E-4

Important Trigonometric Math class Methods


1. sin(x): This method returns the trigonometric sine value of a double value between -1 to 1. It returns the trigonometric sine of an angle. The general method definition is:

public static double sin(double x)

Here, x is an angle in radians.

2. cos(x): This method returns the trigonometric cosine value of a double value between -1 to 1. The general method signature is:

public static double cos(double a)

Here, the parameter x is an angle in radians.

3. tan(x): This method returns the trigonometric tangent value of a double value. It returns the trigonometric tangent of an angle. The general method definition is:

public static double tan(double x)

Here, the parameter x is an angle in radians.

Find trigonometric sine, cos, and tan of angle in Java


Let’s write a Java program to find out the trigonometric sin, cos, and tan of an angle.

Program code 1:

public class Trigonometric {
public static void main(String[] args) 
{
  double x = 20;   
  System.out.println("Math.sin(20): " +Math.sin(x));
  System.out.println("Math.cos(20): " +Math.cos(x));
  System.out.println("Math.tan(20): " +Math.tan(x));
 }
}
Output:
      Math.sin(20): 0.9129452507276277
      Math.cos(20): 0.40808206181339196
      Math.tan(20): 2.237160944224742

Angular Math class Methods in Java


1. toDegrees(x): This method converts the specified radians angle to equivalent angle measured in degrees. The general method signature is:

public static double toDegrees(double x)

Here, x is an angle in radians that has to be converted in degrees.

2. toRadians(x): This method converts the specified degrees angle to the equivalent angle measured in radians. The method signature is:

public static double toRadians(double x)

Here, x is an angle in degrees that has to be converted into radians. Let’s take an example program on both methods.

Program code 1:

public class AngularMethodsExample {
public static void main(String[] args) 
{
  double x = Math.PI;   
  System.out.println("Math.toRadians(x): " +Math.toRadians(x));
  System.out.println("Math.toDegrees(x): " +Math.toDegrees(x));
 }
}
Output:
     Math.toRadians(x): 0.05483113556160755
     Math.toDegrees(x): 180.0

In this tutorial, you learned about Math class in Java and its various methods with example programs. Hope that you will have understood about Math class and practiced all programs.
Thanks for reading!!!
Next ⇒ Java IO⇐ Prev Next ⇒