• Lessons Home
Topics
Community
  1. Lessons
  2. Arithmetic & Logic
  3. Arithmetic Operators
  4. Integer Division and Modulus

      Integer Division and Modulus

      Integer Division and Modulus

      Division in Apex has a surprise for beginners: when both numbers are Integers, the result is also an Integer. The decimal part is cut off, not rounded.

      Integer result = 7 / 2;
      System.debug(result); // 3, not 3.5
      

      Keeping the Decimal Part

      If you need the fraction, make at least one side of the division a Decimal. You can use a Decimal literal or cast one of the values:

      Decimal exact = 7.0 / 2; // 3.5
      Decimal alsoExact = (Decimal) 7 / 2; // 3.5
      

      Finding the Remainder with Math.mod

      Many languages use the % operator to get the remainder of a division. Apex does not have a % operator. Instead, you call the Math.mod method:

      Integer remainder = Math.mod(10, 3); // 1, because 10 = 3 * 3 + 1
      Integer evenSplit = Math.mod(20, 5); // 0, because 20 divides evenly by 5
      

      Where the Remainder Shows Up

      The remainder is handy in many everyday coding tasks:

      • Even or odd: Math.mod(n, 2) is 0 for even numbers and 1 for odd positive numbers
      • Wrapping around: Math.mod(hour + 5, 24) wraps a clock time past midnight
      • Splitting into groups: Math.mod(index, groupSize) gives the position of an item within its group

      Whenever a problem repeats in cycles, think of Math.mod.

      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