Start learning free

LESSON 20 OF 414 · CALCULATIONS WITH NUMBERS

Operator Precedence in Kotlin

Lesson

TL ; DR:

  • When we string operations together, Kotlin must know which one to do first. This is called operator precedence.


  • * and / are performed before + and -:

  • println(1 + 2 * 3) // Prints 7
    println(6 - 4 / 2) // Prints 4
    println(5 * 4 - 2 / 2) // Prints 19
    

  • We can add () to force an operation to be performed first:

    println((1 + 2) * 3) // Prints 9
    println((6 - 4) / 2) // Prints 1
    println(5 * (4 - 2) / 2) // Prints 5
    


Full lesson:

When we string operations together, Kotlin must know which one to do first. This is called operator precedence.

This is the hierarchy from highest precedence to lowest precedence:

  • Parentheses are always respected
  • Multiplication, Division and Remainder
  • Addition and Subtraction
  • Left to right


First example:

println(1 + 2 * 3) // Output: 7

Multiplication is executed before addition, so:

1 + 2 * 3 = 1 + 6 = 7

Second example:

println((1 + 2) * 3) // Output: 9

What's inside parentheses is executed before multiplication, so:

(1 + 2) * 3 = 3 * 3 = 9

Third example:

println(6 / 4 * 3 + 5) // Output: 8

Multiplication and division come before addition. Also, multiplication and division have the same priority so they are executed from left to right. Both numbers in 6 / 4 are Int, so the division drops the fractional part and gives 1:

6 / 4 * 3 + 5 = 1 * 3 + 5 = 3 + 5 = 8

Forth example:

println(6 / ((4 + 2) / 3)) // Output: 3

Computer sees parentheses so it looks at it like this:

6 / ((4 + 2) / 3) = 6 / x, where x = (4 + 2) / 3

I have to compute x first. Parantheses are executed before division:
(4 + 2) / 3 = 6 / 3 = 2

I can replace x with 2:
6 / ((4 + 2) / 3) = 6 / 2 = 3


Assignment
Follow the Coding Tutorial and let's practice with operator precedence!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check