Math methods
Java has a toolbox of ready-made calculations in Math. You call them with values in parentheses, and they give back a result that you can store or print:
| Call | Gives back | Example |
|---|---|---|
Math.sqrt(x) |
the square root of x, as a double |
Math.sqrt(9) is 3.0 |
Math.pow(a, b) |
a to the power b, as a double |
Math.pow(2, 10) is 1024.0 |
Math.max(a, b) |
the larger of the two | Math.max(3, 8) is 8 |
Math.min(a, b) |
the smaller of the two | Math.min(3, 8) is 3 |
Math.abs(x) |
x without its minus sign |
Math.abs(-5) is 5 |
int a = 3;
int b = 4;
double hypotenuse = Math.sqrt(a * a + b * b);
System.out.println(hypotenuse);
System.out.println(Math.max(a, b));
System.out.println(Math.pow(a, 3));
5.0
4
27.0Math.max and Math.min keep the type they're given (two ints give an int), while Math.sqrt and Math.pow always give a double. A call can be part of a bigger calculation, and a call can even go inside another: Math.max(a, Math.max(b, c)) is the largest of three.