• Lessons Home
Topics
Community
  1. Lessons
  2. Arithmetic & Logic
  3. Arithmetic Operators
  4. The Math Class

      The Math Class

      The Math Class

      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).

      A Quick Tour

      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.

      Reach for Math First

      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.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In