Java
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.
Math
The Math class is defined in the java.lang package.
More on packages in the later part of this tutorial series.
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.
functionName
In the following example we will use the Math.sqrt(x) to compute the square root of a number.
Math.sqrt(x)
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
To find the max value we use the Math.max(a, b).
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); } }
$ javac MaxExample.java $ java MaxExample Max value is 20.0
To find the value of x raised to y i.e., xy we use Math.pow(x, y).
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); } }
$ javac PowExample.java $ java PowExample Result: 1024.0
The following table contains the maths functions provided by the Math class.
sin(x)
cos(x)
tan(x)
pow(x, y)
xy
log(x)
ceil(x)
floor(x)
abs(x)
max(a, b)
min(a, b)
Note! a and b can be int, long, float and double.
a
b
int
long
float
double
Whereas, x and y are double.
x
y