Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Order of Operations | Variables and Data Types
Introduction to Scala
course content

Course Content

Introduction to Scala

Introduction to Scala

1. Getting Started
2. Variables and Data Types
3. Conditional Statements and Loops
4. Arrays
5. Strings

bookOrder of Operations

When combining multiple mathematical operations within one expression it is important to be aware of their order of execution. Luckily, Scala follows the order of these operations in mathematics.

1. Parentheses ()

Operations within parentheses () are performed first. This applies to nested parentheses, where the innermost set is evaluated first.

Let's take a look at an example:

java

Main

copy
123456
object Main { def main(args: Array[String]): Unit = { val result = (2 + 3) * 4 println(result) } }

In the expression (2 + 3) * 4, the addition within the parentheses is performed before the multiplication, so the result is 20.

2. Multiplication, Division, and Remainder

These operations have the next highest precedence after parentheses. They are evaluated from left to right. Let's take a look at an example to make things clear:

java

Main

copy
123456
object Main { def main(args: Array[String]): Unit = { val result = 2 + 3 * 4 % 5 / 2 println(result) } }

Since there are no parentheses in our expression multiplication, division, and remainder operations are executed first. The leftmost such operation is 3 * 4, so it's evaluated first, the result is 12. Next, we go to the right and evaluate 12 % 5 resulting in 2. Afterward, we evaluate 2 / 2 resulting in 1. Finally, the last operation is addition (2 + 1), so the final result is 3.

3. Addition and Subtraction

These operators have lower precedence than multiplication, division, and remainder. They are also evaluated from left to right.

java

Main

copy
123456
object Main { def main(args: Array[String]): Unit = { val result = 5 - 2 + 3 * 4 % 5 / 2 println(result) } }

As you can see, this example is similar to the previous one, so the subtraction and addition operations are performed last. Since we evaluate from left to right subtraction (5 - 2) is calculated first resulting in 3. Next, the addition is performed (3 + 1) resulting in 4 since 3 * 4 % 5 / 2 is equal to 1.

Select the correct value of the result variable.

Select the correct value of the result variable.

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 6
some-alt