All lessons

Numbers & Math

7 min · Kotlin

Do math with variables and the basic operators.

Kotlin · Numbers & Math0/5 cleared

Enemy 1 of 5

Kotlin uses the same basic arithmetic operators as most languages: + for addition, - for subtraction, * for multiplication, and / for division. You can perform math directly on literal numbers, or (much more commonly in real programs) store numbers in variables first and then combine the variables, since real values usually come from user input or an earlier calculation rather than being hand-typed.

To print the result of a calculation, just place the expression directly inside println's parentheses: println(price * quantity) — Kotlin evaluates price * quantity first and prints the resulting number. This is a bit more direct than Rust, where you generally need a {} placeholder in a format string; Kotlin lets you pass the value straight in.

A gotcha worth knowing early: dividing two Int values with / performs integer division, truncating any remainder rather than giving a decimal — so 7 / 2 evaluates to 3, not 3.5. To get a fractional answer, at least one operand needs to be a Double (for example, 7.0 / 2). This behavior is shared with Java, C, Rust, and most statically typed languages, and it surprises nearly everyone the first time they hit it.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 15