← Back to Scala Course | Chapter 3: Operators & Expressions | Lesson 1 of 7

Arithmetic Operators

Arithmetic operators are the calculator buttons: add, subtract, multiply, divide, and find the remainder. Scala uses them to do math with numbers and variables.

In this page:

  1. Arithmetic Operators
Syntax
scala
a + b
a - b
a * b
a / b
a % b

Arithmetic Operators

Scala provides +, -, *, /, and % for arithmetic, all implemented as methods on numeric types (Scala has no truly special-cased operators).

Integer division truncates any fractional part, while dividing two Doubles keeps precision. % returns the remainder of a division.

Warning: Dividing two Ints, like 7 / 2, gives 3, not 3.5 -- make at least one operand a Double to get a fractional result.

Example: Arithmetic Operators

markup
object Main extends App {
  val a = 7
  val b = 2

  println(a + b)
  println(a - b)
  println(a * b)
  println(a / b)          // integer division
  println(a % b)          // remainder
  println(a.toDouble / b) // fractional division
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using / on two Int values and expecting a decimal, when 7 / 2 is 3; use 7.0 / 2.
  2. Dividing an Int by 0, which throws an ArithmeticException, while a Double gives Infinity.
  3. Using ^ for exponents, when it is bitwise XOR and you need math.pow(a, b).
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.