Start learning free

LESSON 16 OF 348 · CALCULATIONS WITH NUMBERS

Arithmetic Operators in Kotlin

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, Kotlin will replace variable num with its value 6 to do the calculations:

    val 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:
val a = 2
val b = 3

println(a + b) // Output: 5

println(a + 10) // Output: 12

Subtraction

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

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

println(10 - b) // Output: 7

Multiplication

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

println(a * 5) // Output: 10

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

Division

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

// Declare 2 integer variables and initialize them:
val a = 2
val 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:
val a = 2
val b = 3

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

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

    KOTLIN · CALCULATIONS WITH NUMBERS

    Arithmetic Operators in Kotlin, explained

    What arithmetic operators do

    Kotlin has five arithmetic operators, and they work on numbers the way you expect from school mathematics: + adds, - subtracts, * multiplies, / divides and % gives the remainder of a division. Each one takes a value on its left and a value on its right, and each can be used with plain numbers, with variables, or with a mix of both.

    val a = 2
    val b = 3
    
    println(a + b)      // 5
    println(a - b)      // -1
    println(a * 5)      // 10
    println(2 * a * b)  // 12
    

    When Kotlin sees a variable in an expression, it replaces the variable with its current value. Doing arithmetic on a variable never changes the variable. After println(a + b), both a and b still hold 2 and 3. The only way to change what a variable holds is to assign to it with = (and only a var allows that; a val is fixed once set).

    Division needs care

    Division is the operator that surprises beginners. In Kotlin, the type of the result follows the types of the operands. If both sides are integers (Int), the result is an integer too, and the fractional part is thrown away:

    val a = 2
    val b = 3
    
    println(20 / 3)  // 6
    println(b / a)   // 1
    

    Integer division truncates toward zero, so -7 / 2 is -3, not -4. If you want the fractional part, at least one side must be a Double. You can write a decimal literal such as 2.0, or convert a value with toDouble():

    val a = 2
    val b = 3
    
    println(7.toDouble() / 3)  // 2.3333333333333335
    println(b / a.toDouble())  // 1.5
    println(7 / 2.0)           // 3.5
    

    A common trap is converting too late. (7 / 2).toDouble() divides two integers first, gets 3, and only then converts it to 3.0. Convert one operand before the division, as in the examples above.

    The remainder operator

    The % operator gives what is left over after a division. 20 % 3 is 2, because 3 fits into 20 six times with 2 left. Together, / and % on integers satisfy (a / b) * b + a % b == a. The result of % takes the sign of the left operand, so -7 % 3 is -1.

    Int is 32 bits

    An Int holds values from -2147483648 to 2147483647. If a calculation goes past that range, Kotlin does not warn you: the result wraps around.

    val big = 2147483647
    println(big + 1)             // -2147483648
    println(big.toLong() + 1)    // 2147483648
    

    For the small numbers in this lesson that never matters, but it is worth knowing before you multiply large values. Use Long when results can get big.

    The exercise

    The variable price holds the cost of one product, 83. Andy buys 4 products at that price and one bag for 15, and the task is to print the total he pays.

    1. Multiply the quantity by the price. Four products at price each cost 4 * price.
    2. Add the bag. The bag costs a fixed 15, so it is added to the product cost.
    3. Print the whole expression. println accepts any expression, so there is no need for an extra variable.

    Because * is evaluated before +, the multiplication happens first without any parentheses.

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

    The output is 347: 4 times 83 is 332, and 332 plus 15 is 347. The type annotation : Int is optional, since Kotlin would infer Int from the literal 83. Writing it just makes the type visible.

    Common mistakes

    • Expecting a decimal from integer division. 3 / 2 is 1. Use 3 / 2.0 or 3.toDouble() / 2 for 1.5.
    • Dividing by zero. Integer division or remainder by zero throws an ArithmeticException with the message / by zero. With Double values, 1.0 / 0 prints Infinity instead.
    • Assuming a variable changed. Writing price * 4 on its own line computes a value and discards it; price keeps its old value.
    • Looking for a power operator. Kotlin has no operator for powers. Library functions do that job.

    Key takeaways

    • +, -, *, / and % work with numbers and with variables holding numbers.
    • Arithmetic never changes a variable; only assignment does.
    • Dividing two Int values drops the fractional part; make one side a Double to keep it.
    • Int overflow wraps silently, so reach for Long when numbers can grow large.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free