Java Math Class with Examples

Java Math class with Examples | The Math class in Java is available in java.lang package. Since java.lang package is the default package to every Java program, therefore there is no need to import the Math class explicitly in the program.

Java Math class contains several methods for performing basic numeric operations such as elementary exponential, logarithm, square root, cubic root, absolute value, max value, and trigonometric functions.

By default, many of the Math methods simply call the equivalent method in StrictMath class for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math class methods.

Note:- We can’t create objects of the Java Math class.

Math class contains two public static final variables. Those are,

VariableValue
PI3.14159265358979323846
E2.7182818284590452354
public class Test {
   public static void main(String[] args) {
       System.out.println(Math.PI);
       System.out.println(Math.E);
   }
}

Output:-

3.141592653589793
2.718281828459045

Instead of calling static members of the Math class through its class name, we can use a static import statement. Learn more:- import math class in Java.

Java Math Class Methods

Return typeMethodDescription
doublepow(double a, double b)Returns ab
doubleexp(double x)Returns ex , where e is Euler’s number.
doubleexpm1(double x)Returns ex -1.
doublelog(double x)Returns the natural logarithm base e of x.
doublelog10(double x)Returns the base 10 logarithms of x.
doublelog1p(double x)Returns the natural logarithm of x+1
doublesqrt(double x)Returns square root value of x.
doublecbrt(double x)Returns the cube root value of x.
doubleceil(double x)Returns the smallest double value that is greater than or equal to x and is equal to a mathematical integer..
doublefloor(double x)Returns the largest double value that is less than or equal to x and is equal to a mathematical integer.
doublerint(double x)Returns the double value that is closest in value to x and is equal to a mathematical integer.
intround(float a)Returns the closest int to x, with ties rounding to positive infinity.
longround(double a)Similar to the previous one, the argument and return type changed.
doublerandom()Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0
public class Test {
   public static void main(String[] args) {
      System.out.println(Math.pow(2, 3)); 

      System.out.println(Math.exp(1));
      System.out.println(Math.expm1(1));

      System.out.println(Math.log(11));
      System.out.println(Math.log10(10));
      System.out.println(Math.log1p(10));

      System.out.println(Math.sqrt(64));
      System.out.println(Math.cbrt(64));
   }
}

Output:-

8.0
2.718281828459045
1.718281828459045
2.3978952727983707
1.0
2.3978952727983707
8.0
4.0

Another example,

public class Test {
   public static void main(String[] args) {
      System.out.println(Math.ceil(5.5));
      System.out.println(Math.floor(5.5));
      System.out.println(Math.rint(5.5));
      System.out.println(Math.round(5.5));
   }
}

Output:-

6.0
5.0
6.0
6

Differences between ceil(), floor(), rint(), and round() methods

xceil(x)floor(x)rint(x)round(x)
9.09.09.09.09
9.310.09.09.09
9.510.09.010.010
9.710.09.010.010
-9.0-9.0-9.0-9.0-9
-9.3-9.0-10.0-9.0-9
-9.5-9.0-10.0-10.0-9
-9.7-9.0-10.0-10.0-10

Note:- The value of Math.ceil(x) is exactly the value of -Math.floor(-x).

Math.ceil(x) = -Math.floor(-x).

public class Test {
   public static void main(String[] args) {
      for(int i=0; i<5; i++) {
         System.out.println(Math.random());
      }
   }
}

Output:-

0.49644420181133186
0.9310877968057992
0.1530478942321487
0.16209426500591828
0.5641161302608104

Methods with multiple overloaded forms

Methoddescription
abs()It returns the absolute value of the passed value.
max()It returns the greater of two passed values.
min()It returns the smaller of two passed values.

The overloaded forms of Math.abs() are,

  • public static int abs(int a)
  • public static long abs(long a)
  • public static float abs(float a)
  • public static double abs(double a)

Overloaded forms of Math.max() are,

  • 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)

The overloaded forms of Math.min() are,

  • 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)

Program to demonstrate these methods.

public class Test {
   public static void main(String[] args) {
      int a = 10, b = -20;
      System.out.println(Math.abs(a)); // 10
      System.out.println(Math.abs(b)); // 20
      System.out.println(Math.max(a, b)); // 10
      System.out.println(Math.min(a, b)); // -20
   }
}

Java Math class Methods for angle conversion

Return typeMethodDescription
doubletoRadians(double angdeg)It converts an angle measured in degrees to an approximately equivalent angle measured in radians.
doubletoDegrees(double angrad)It converts an angle measured in radians to an approximately equivalent angle measured in degrees.

Program to convert degree to radian

public class Test {
   public static void main(String[] args) {
      // take one value in degree
      double degree = 45;

      // convert to radian
      double radian = Math.toRadians(degree);

      // display value
      System.out.println(radian);
   }
}

Output:-

0.7853981633974483

Program to convert radian to degree

public class Test {
   public static void main(String[] args) {
      // take one value in radian
      double radian = 5;

      // convert to  degree
      double degree = Math.toDegrees(radian);

      // display value
      System.out.println(degree);
   }
}

Output:-

286.4788975654116

Trigonometry-related Java Math class methods

Return typeMethodDescription
doublesin(double a)It returns the trigonometric sine of an angle in radian.
doublecos(double a)It returns the trigonometric cosine of an angle in radian
doubletan(double a)Returns the trigonometric tangent of an angle in radian

Important points on sin(), cos() and tan() methods

  • The argument value must be in radians.
  • If the argument is NaN or an infinity, then these three method return NaN.

And in the case of sin() and tan(), If the argument is zero, then the result is a zero with the same sign as the argument.

public class Test {
   public static void main(String[] args) {
      // take one value in degree
      double degree = 45;

      // convert to radian
      double radian = Math.toRadians(degree);

      // display sin, cos, tan values
      System.out.println(Math.sin(radian));
      System.out.println(Math.cos(radian));
      System.out.println(Math.tan(radian));
   }
}

Output:-

0.7071067811865475
0.7071067811865476
0.9999999999999999

// Special cases
Math.sin(Double.NaN) => NaN
Math.cos(Double.POSITIVE_INFINITY) => NaN
Math.tan(Double.NEGATIVE_INFINITY) => NaN
Math.sin(0.0) => 0.0
Math.sin(-0.0) => -0.0
Math.tan(0.0) => 0.0
Math.tan(-0.0) => -0.0

Return typeMethodDescription
doubleasin(double a)It returns the arc sine of a value;
doubleacos(double a)It returns the arc cosine of a value
doubleatan(double a)Returns the arc tangent of a value

Points on asin(), acos() and atan() method

  • The argument value should be within the range of -1 to 1.
  • Else result is NaN.

And in the case of asin() and atan(), If the argument is zero, then the result is a zero with the same sign as the argument.

public class Test {
   public static void main(String[] args) {
      System.out.println(Math.asin(2));
      System.out.println(Math.asin(1));
      System.out.println(Math.atan(-1));
      System.out.println(Math.acos(0.5));
  }
}

Output:-

NaN
1.5707963267948966
-0.7853981633974483
1.0471975511965979

Other methods are,

Return typeMethodDescription
doublesinh(double x)Returns the hyperbolic sine of x.
doublecosh(double x)Returns the hyperbolic cosine of x.
doubletanh(double x)Returns the hyperbolic tangent of x.
doubleatan2(double y, double x)Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).

Special cases on sinh(), cosh() and tanh(),

xsinh(x)cosh(x)tanh()
NaNNaNNaNNaN
zeroZero with the same sign1.0Zero with the same sign
positive infinitypositive infinitypositive infinity+1.0
negative infinitynegative infinitypositive infinity-1.0

Java Math class methods to perform basic arithmetic operations

Important points on these methods

  • They return either int/long value.
  • They were added to Java 1.8 onwards.
  • Most of them have overloaded forms, but they perform similar operations.
  • They throw ArithmeticException.

Since ArithmeticException is unchecked exceptions so no need to handle them. Here we listed methods having a higher range argument/return type.

Return typeMethodsdescription
longaddExact(long x, long y)Returns the sum of its arguments
longsubtractExact(long x, long y)Returns the difference of the arguments.
longmultiplyExact(long x, long y)Returns the product of the arguments
longfloorDiv(long x, long y)Returns the largest long value that is less than or equal to the algebraic quotient.
longfloorMod(long x, long y)Returns the floor modulus of the long arguments.
longincrementExact(long a)Returns the argument incremented by one.
longdecrementExact(long a)Returns the argument decremented by one.
longnegateExact(long a)Returns the negation of the argument.
inttoIntExact(long value)Returns the int value of the long argument

The floorDiv() and floorMod() throw ArithmeticException if the divisor (y) is zero, and the remaining methods throw ArithmeticException if the result overflows the return type value.

See overloaded forms

All these methods were added in Java 1.8 but some overloaded forms were added in Java 9 version also.
List of these methods with all its overloaded forms:-
• public static int addExact(int x, int y)
• public static long addExact(long x, long y)
• public static int subtractExact(int x, int y)
• public static long subtractExact(long x, long y)
• public static int multiplyExact(int x, int y)
• public static long multiplyExact(long x, int y) Since Java9
• public static long multiplyExact(long x, long y)
• public static int floorDiv(int x, int y)
• public static long floorDiv(long x, int y) Since Java9
• public static long floorDiv(long x, long y)
• public static int floorMod(int x, int y)
• public static int floorMod(long x, int y) Since Java9
• public static long floorMod(long x, long y)
• public static int incrementExact(int a)
• public static long incrementExact(long a)
• public static int decrementExact(int a)
• public static long decrementExact(long a)
• public static int negateExact(int a)
• public static long negateExact(long a)
• public static int toIntExact(long value) (No overloaded form)

Examples

Demonstrating addExact(), subtractExact(), multiplyExact(), floorDiv(), and floorMod() methods.

public class Test {
   public static void main(String[] args) {
   
      // variables
      int a = 20;
      int b = 5;

      System.out.println(Math.addExact(a, b)); // 25
      System.out.println(Math.subtractExact(a, b)); // 15
      System.out.println(Math.multiplyExact(a, b)); // 100

      System.out.println(Math.floorDiv(a, b)); // 4
      System.out.println(Math.floorMod(a, b)); // 0
      System.out.println(Math.floorMod(12, 9)); // 3
  }
}

Compared to increment (++) and decrement (- -) operators, the incrementExact() and decrementExact() are method returning values. These operators perform the operations and are assigned to the variable itself, no need to do it explicitly but while working with methods we need to assign the return value to the variables.

public class Test {
   public static void main(String[] args) {
   
      // variables
      int a = 20;
      int b = 10;

      // methods won't assign return values to 
      // the passed variable
      System.out.println(Math.incrementExact(a)); // 21
      System.out.println(a); // 20
      System.out.println(Math.decrementExact(a)); // 19
      System.out.println(a); // 20

      // operators perform the operations
      // and assign it to the variables
      System.out.println(++b); // 11
      System.out.println(b); // 11
      System.out.println(--b); // 10
      System.out.println(b); // 10
      
      // while working with methods
      // we must assign it explicitly
      a = Math.incrementExact(a);
      System.out.println(a); // 21
      a = Math.decrementExact(a);
      System.out.println(a); // 20
  }
}

Demonstrating negateExact() and toIntExact() methods.

public class Test {
   public static void main(String[] args) {
      // variables
      int a = 20;

      System.out.println(Math.negateExact(a)); // -20
      System.out.println(a); // 20
      
      a = Math.negateExact(a);
      System.out.println(a); // -20

      System.out.println(Math.toIntExact(50L)); // 50
  }
}

Cases when ArithmeticException is raised by these methods.

// variables
long a = Long.MAX_VALUE;
long b = Long.MIN_VALUE;

// all of these operations throws
// java.lang.ArithmeticException
Math.addExact(a, 10); // long overflow
Math.subtractExact(a, -10); // long overflow
Math.multiplyExact(a, 10); // long overflow

Math.floorDiv(a, 0); // / by zero
Math.floorMod(a, 0); // / by zero

Math.incrementExact(a); // long overflow
Math.decrementExact(b); // long overflow
Math.negateExact(b); // long overflow
Math.toIntExact(a); // integer overflow

Other Methods

These methods have some overloaded forms.

MethodsDescription
double fma(double a, double b, double c)Returns the fused multiply-add of the three arguments; that is, returns the exact product of the first two arguments summed with the third argument and then rounded once to the nearest double.
double ulp(double d)Returns the size of an ulp of the argument.
double signum(double x)Returns the signum function of x; i.e. 0 if x=0, 1.0 if x>0, -1.0 if x<0
double hypot(double x, double y)It returns sqrt(x2+y2) without intermediate overflow or underflow.
double copySign(double magnitude, double sign)Returns the first floating-point argument with the sign of the second floating-point argument.
int getExponent(double d)Returns the unbiased exponent used in the representation of x
double nextAfter(double start, double direction)Returns the floating-point number adjacent to the first argument in the direction of the second argument. If both arguments compare as equal the second argument is returned.
double nextUp(double d)Returns the floating-point value adjacent to d in the direction of positive infinity.
double nextDown(double d)Returns the floating-point value adjacent to d in the direction of negative infinity.
double scalb(double d, int scaleFactor)Returns d x 2 scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the double value set.

Java Math class Methods added after Java1.8

Java.lang.Math class methods added in Java 9 version,

Return typeMethodsdescription
longmultiplyFull(int x, int y)Returns the exact mathematical product of the arguments.
longmultiplyHigh(long x, long y)Returns as long the most significant 64 bits of the 128-bit product of two 64-bit factors.

Java.lang.Math class methods added in Java 15 version

absExact(x):- Returns the mathematical absolute value x value if it is exactly representable as a long. Its overloaded forms are,

  • public static int absExact(int a)
  • public static long absExact(long a)

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *