Operators
An operator is a symbol that performs an action on values: adds them, compares them, combines conditions. The values it works on are called operands: in 2 + 3 the operator is + and the operands are 2 and 3.
Arithmetic
Addition, subtraction and multiplication work as usual. The % operator gives the remainder of a division:
void main() {
IO.println(7 + 2);
IO.println(7 - 2);
IO.println(7 * 2);
IO.println(7 % 2);
}Output:
9
5
14
1The remainder is handy for checking parity: a number is even when n % 2 equals zero.
Division
If both operands are whole numbers, the result is a whole number too — the fractional part is simply dropped. To get a fractional answer, at least one number must be a double:
void main() {
IO.println(7 / 2);
IO.println(7.0 / 2);
}Output:
3
3.5Compound assignment
x += 5 is a short form of x = x + 5. -=, *=, /= and %= work the same way. To increase or decrease by one there are the ++ and -- operators:
void main() {
int count = 10;
count += 5;
count *= 2;
count++;
IO.println(count);
}Output:
31Comparison
Comparison operators return a boolean: == (equal), != (not equal), <, >, <=, >=. Note that equality uses two = signs; a single one is assignment:
void main() {
int age = 20;
IO.println(age >= 18);
IO.println(age == 21);
IO.println(age != 21);
}Output:
true
false
trueLogical operators
Logical operators combine conditions: && (and) is true when both conditions are true; || (or) when at least one is; ! (not) flips a value:
void main() {
int age = 25;
boolean hasTicket = false;
IO.println(age >= 18 && hasTicket);
IO.println(age >= 18 || hasTicket);
IO.println(!hasTicket);
}Output:
false
true
trueThere are also operators that work with the individual bits of a number — see the bitwise operators lesson.
Order of evaluation
As in math, multiplication and division happen before addition and subtraction. Parentheses change the order:
void main() {
IO.println(2 + 3 * 4);
IO.println((2 + 3) * 4);
}Output:
14
20When in doubt about the order, add parentheses — the code becomes clearer.
Common mistake
Integer division silently loses the fractional part. Here the average of two grades should be 4.5, but we get 4:
void main() {
int a = 4;
int b = 5;
double average = (a + b) / 2;
IO.println(average);
}Output:
4.09 / 2 was computed as integer division before the value went into the double. Divide by 2.0 and the result is 4.5.