Java Tutorial
Java Math
Math gives sqrt, pow, round, and abs. Use them instead of writing formulas by hand.
Common functions
Math.sqrt, Math.pow, Math.abs, Math.round, Math.min, and Math.max live on the Math class. You do not import it.
Example
public class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(64.0));
System.out.println(Math.pow(2.0, 10.0));
System.out.println(Math.abs(-12));
}
}Hypotenuse
Math.hypot(x, y) is the square root of x² + y² without overflowing as easily as a hand-written formula.
Example
public class Main {
public static void main(String[] args) {
System.out.println(Math.hypot(3.0, 4.0));
}
}Min and max
Math.max of three values nests: Math.max(a, Math.max(b, c)).
Example
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(8, Math.max(11, 5)));
}
}Rounding returns a whole number
Math.round gives the nearest integer, Math.ceil always rounds up, andMath.floor always rounds down. Note that ceil and floor return adouble, so cast to int when you want a plain whole number.
Example
public class Main {
public static void main(String[] args) {
System.out.println(Math.round(3.7)); // 4
System.out.println((int) Math.ceil(3.1)); // 4
System.out.println((int) Math.floor(3.9));// 3
}
}Many Math methods want double arguments and give back a double. If you need an int result, cast it: (int) Math.sqrt(64).
Random numbers
Math.random() returns a double from 0.0 up to (but not including) 1.0. Scale and cast it to get a dice roll or a random index.
Example
public class Main {
public static void main(String[] args) {
int roll = (int) (Math.random() * 6) + 1; // 1..6
System.out.println(roll);
}
}Try It Yourself
Exercise: Given double a = 6, b = 8, print the length of the hypotenuse, then print it rounded to the nearest whole number.
Show solution
double a = 6, b = 8;
double h = Math.hypot(a, b);
System.out.println(h); // 10.0
System.out.println(Math.round(h)); // 10Here the answer is exactly 10, but Math.round is what you would reach for whenever the result has a fractional part.
Key Takeaways
Mathgivessqrt,pow,abs,min,max,hypot— no import needed.round/ceil/floorreturn whole-number values; cast tointwhen you need one.Math.random()gives 0.0 up to 1.0 — scale and cast for dice or indexes.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.
Physics
Hypotenuse of a force
Two perpendicular components add as a Pythagorean sum. Math.hypot does the square root of the sum of squares.
F = √(Fx² + Fy²)
Example
public class Main {
public static void main(String[] args) {
System.out.println(Math.hypot(5.0, 12.0) + " N");
}
}