Java - Math

Java

Share

In this tutorial we will learn about math functions provided by the Math class in Java programming language.

Java provides us the Math class which contains mathematical functions like sin, cos, tan etc. to perform math operations.

The Math class is defined in the java.lang package.

More on packages in the later part of this tutorial series.

How to use the math function?

We use the following syntax to use the math functions of the Math class.

Math.functionName(param);

And we get some value that is returned by the functionName.

Example #1: Write a program in Java to find the square root of x

In the following example we will use the Math.sqrt(x) to compute the square root of a number.

class SqrtExample {
  public static void main(String args[]) {
    double x = 16;
    double sqrt = Math.sqrt(x);
    System.out.println("Square root of " + x + " is " + sqrt);
  }
}

Output:

$ javac SqrtExample.java 
$ java SqrtExample
Square root of 16.0 is 4.0

Example #2: Write a program in Java to find the max value of a and b

To find the max value we use the Math.max(a, b).

class MaxExample {
  public static void main(String args[]) {
    double a = 10;
    double b = 20;
    double max = Math.max(a, b);
    System.out.println("Max value is " + max);
  }
}

Output:

$ javac MaxExample.java 
$ java MaxExample
Max value is 20.0

Example #3: Write a program in Java to find the value of xy

To find the value of x raised to y i.e., xy we use Math.pow(x, y).

class PowExample {
  public static void main(String args[]) {
    double a = 2;
    double b = 10;
    double pow = Math.pow(a, b);
    System.out.println("Result: " + pow);
  }
}

Output:

$ javac PowExample.java 
$ java PowExample
Result: 1024.0

The following table contains the maths functions provided by the Math class.

Method Description
sin(x) Returns the sine of the angle x in radians.
cos(x) Returns the cosine of the angle x in radians.
tan(x) Returns the tangent of the angle x in radians.
pow(x, y) Returns x raised to power y i.e. xy.
log(x) Returns natural log of x.
ceil(x) Returns the smallest whole number greater than or equal to x.
floor(x) Returns the largest whole number less than or equal to x.
abs(x) Returns the absolute value of x.
max(a, b) Returns the maximum value of a and b.
min(a, b) Returns the minimum value of a and b.

Note! a and b can be int, long, float and double.

Whereas, x and y are double.

Share