Start learning free

LESSON 16 OF 414 · CALCULATIONS WITH NUMBERS

Arithmetic Operators in Scala: +, -, *, / and %

Lesson Read the full explanation

TL ; DR:

  • We can tell computers to perform calculations for us using +, -, *, /:

    println(2 + 6) // Prints 8
    println(10 - 7) // Prints 3
    println(3 * 3) // Prints 9
    println(6 / 2) // Prints 3
    


  • We can also use variables. In these examples, Scala will replace variable num with its value 6 to do the calculations:

    var num = 6
    println(num + 5) // Prints 11
    println(10 - num) // Prints 4
    println(3 * num) // Prints 18
    println(num / 2) // Prints 3
    



Full lesson:

Computers absolutely excel at performing calculations. The "compute" in their name comes from their historical association with providing answers to mathematical questions.

These calculations can be performed either directly with numbers or with variables that are assigned numeric values.

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Examples
+ Addition 3 + 5,  x + 5,  3 + y,  x + y
- Subtraction 8 - 3,  8 - y,  x - 3,  x - y
* Multiplication 3 * 5,  3 * y,  x * 5,  x * y
/ Division 8 / 4,  8 / y,  x / 8,  x / y
% Modulus 8 % 4,   8 % y,  x % 4,  x % y


Note that performing arithmetic on variables does not change the variable - you can only update a variable using the = sign.

Let's go through some examples together to better understand how each operator works:


Addition

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println(a + b) // Output: 5

println(a + 10) // Output: 12

Subtraction

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println(a - b) // Output: -1

println(10 - b) // Output: 7

Multiplication

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println(a * 5) // Output: 10

println(2 * a * b) // Output: 12

Division

In Scala, division between integers returns only the integral part of the result:

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println(20 / 3) // Output: 6

println(b / a) // Output: 1

If we want to get the real result of the division, at least one of the terms has to be of type Double:

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println(7.toDouble / 3) // Output: 2.3333333333333335

println(b / a.toDouble) // Output: 1.5

Assignment
Follow the Coding Tutorial and let's practice with arithmetic operators!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · CALCULATIONS WITH NUMBERS

    Arithmetic Operators in Scala, explained

    What arithmetic operators do

    Arithmetic operators let a program calculate with numbers, either written directly in the code or stored in variables. Scala has five of them:

    OperatorNameExampleResult
    +Addition2 + 68
    -Subtraction10 - 73
    *Multiplication3 * 39
    /Division6 / 23
    %Remainder (modulo)8 % 32

    Put the expression inside println to see its value:

    println(2 + 6)
    println(10 - 7)
    println(3 * 3)
    println(6 / 2)
    println(8 % 3)
    
    8
    3
    9
    3
    2
    

    Using variables

    An operator works the same way on a variable as on a literal number. Scala reads the variable's current value and calculates with it:

    var num = 6
    println(num + 5)
    println(10 - num)
    println(3 * num)
    println(num / 2)
    println(num)
    
    11
    4
    18
    3
    6
    

    The last line shows that num is still 6. An expression produces a new value and leaves the variable alone. Only an assignment with = changes it, and only a var can be assigned again. Assigning to a val is a compile error: Reassignment to val x.

    Division: Int against Double

    Division is where beginners get surprised. The type of the operands decides what / does.

    • If both operands are Int, the result is an Int and the fractional part is dropped (truncated toward zero).
    • If at least one operand is a Double, the result is a Double and keeps the decimals.
    val a = 2
    val b = 3
    println(20 / 3)
    println(b / a)
    println(7.0 / 3)
    println(b.toDouble / a)
    println(b / a.toDouble)
    
    6
    1
    2.3333333333333335
    1.5
    1.5
    

    To get a real quotient from two Int variables, convert one of them with toDouble. Scala does not use the C-style cast (Double) x: writing (Double) 7 / 3 fails to compile with ',' or ')' expected, but integer literal found.

    Truncation goes toward zero, not downward, so negative numbers show it clearly:

    println(-7 / 2)
    println(-7 % 2)
    
    -3
    -1
    

    The remainder takes the sign of the left operand. Dividing an Int by zero throws java.lang.ArithmeticException: / by zero, while dividing a Double by zero gives Infinity, -Infinity or NaN.

    Precedence and Int size

    *, / and % are evaluated before + and -, and operators of equal rank go left to right. Parentheses change the order. An Int is 32 bits, so a result beyond 2147483647 wraps around without any error: Int.MaxValue + 1 is -2147483648. Use Long for larger values.

    Common mistakes

    • Expecting decimals from integer division. 1 / 2 is 0, not 0.5. If a result looks too small, check whether both operands are Int.
    • Forgetting the result is not stored. A line like num + 5 on its own calculates a value and throws it away. Print it, or assign it to a variable such as val total = num + 5.
    • Mixing up / and %. For 15 and 4, 15 / 4 is the quotient 3 and 15 % 4 is the remainder 3. For 20 and 3 they differ: 6 and 2.

    The exercise

    The variable price holds the cost of one product. Andy buys 4 products at that price and one bag for 15 dollars. The total is four times the price plus 15, so the expression combines a multiplication and an addition. Because * binds tighter than +, no parentheses are needed:

    val price: Int = 83
    println(4 * price + 15)
    

    With price equal to 83 this prints 347: 4 * 83 is 332, and 332 + 15 is 347.

    Key takeaways

    • Scala has +, -, *, / and %.
    • Calculating with a variable does not change it; only = does, and only on a var.
    • Int / Int drops the fraction; make one side a Double to keep it.
    • Multiplication, division and remainder come before addition and subtraction.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free