Apex ships with a built-in Math class, a library of static helper methods for common calculations. You never create a Math object; you call the methods directly on the class, such as Math.abs(-5).
Math.abs(-7); // 7 - the distance from zero, always positive Math.max(3, 9); // 9 - the larger of two numbers Math.min(3, 9); // 3 - the smaller of two numbers Math.pow(2, 3); // 8.0 - 2 raised to the power of 3 Math.sqrt(16); // 4.0 - the square root Math.round(4.6); // 5 - rounds to the nearest whole number
Note that Math.pow and Math.sqrt return Double values, so store their results in a Double or Decimal variable.
Before writing your own helper logic, check whether the Math class already does the job:
// Instead of this:
Integer larger;
if (a > b) {
larger = a;
} else {
larger = b;
}
// Write this:
Integer larger = Math.max(a, b);
Using the built-in methods keeps your code shorter, easier to read, and less likely to contain bugs. The Math class has dozens of methods; abs, max, min, pow, sqrt, round, floor, and ceil are the ones you will reach for most often.