Java Math
The Math class holds methods for common maths work. Each call names Math first and then the method.
The larger and the smaller value
The max call reads two values and returns the larger one. The min call returns the smaller one.
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(7, 3));
System.out.println(Math.min(7, 3));
}
}Square root and absolute value
The sqrt call returns the square root of 16. The abs call drops the negative sign from its value.
public class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(16));
System.out.println(Math.abs(-9));
}
}Raise a value to a power
The pow call takes a base and a power. Its result is a double, so the result prints with a decimal point.
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(2, 3));
}
}A random value stays in range
The random call returns a value from 0 up to but not including 1. The range check prints true for every value that call can give.
public class Main {
public static void main(String[] args) {
double value = Math.random();
boolean inRange = value >= 0 && value < 1;
System.out.println(inRange);
}
}Example
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(12, 20));
System.out.println(Math.sqrt(81));
System.out.println(Math.pow(3, 2));
System.out.println(Math.abs(-4));
}
}Key points
- Math.max returns the larger of two values.
- Math.min returns the smaller of two values.
- Math.sqrt returns the square root of a value.
- Math.abs returns a value without its negative sign.
- Math.pow raises a value to a power.
- Math.random returns a double from 0 up to but not including 1.
In this example, the max call picks 20 from 12 and 20. The sqrt call returns 9.0 for 81, and the pow call raises 3 to the power 2 for a second 9.0. The abs call prints 4.
Note
Math.sqrt and Math.pow return double values, so whole results print with a decimal point.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does Math.sqrt(16) print?