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

      Arithmetic Operators

      Arithmetic Operators

      Apex gives you four basic arithmetic operators for working with numbers. You will use them constantly, from adding up order totals to computing discounts.

      OperatorNameExampleResult
      +Addition4 + 37
      -Subtraction9 - 54
      *Multiplication6 * 212
      /Division8 / 24

      Operator Precedence

      Just like in math class, multiplication and division happen before addition and subtraction:

      Integer result = 2 + 3 * 4; // 14, not 20
      

      Apex evaluates 3 * 4 first and then adds 2. When you want a different order, use parentheses:

      Integer result = (2 + 3) * 4; // 20
      

      Parentheses are also a great way to make your intent obvious to other developers, even when they are not strictly required.

      Mixing Integer and Decimal

      When an expression mixes an Integer with a Decimal, the result becomes a Decimal so no precision is lost:

      Decimal price = 9.99;
      Integer quantity = 3;
      Decimal subtotal = price * quantity; // 29.97 (Decimal)
      

      Putting It Together

      Here is a short example that computes an order total:

      Decimal unitPrice = 4.50;
      Integer quantity = 3;
      Decimal shippingFee = 2.25;
      
      Decimal total = unitPrice * quantity + shippingFee;
      System.debug(total); // 15.75
      

      Because * runs before +, the unit price and quantity are multiplied first and the shipping fee is added last, which is exactly what we want.

      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