Card 01/ 09

ConceptDifficulty: Beginner1 min

Operators and Operand Types: One Symbol, Several Jobs

5 + 3 prints 8 and "5" + 3 prints 53, and the symbol is the same in both.

In Java, what an operator does depends on the types of its operands, the values either side of it. The compiler reads those types first and then decides: + adds two numbers but joins a string to anything, and / discards the remainder when both sides are whole numbers.

Two lines that look like arithmetic, and only one of them does any. The difference is not in the symbol; it is in what sits either side of it:

java
System.out.println(5 + 3);
System.out.println("5" + 3);
text
8
53

Two numbers make + addition. One string makes it concatenation, joining two pieces of text, and the number is turned into text to join it.

The same happens quietly with /. Two int values make it whole-number division, which discards the remainder rather than rounding it. One double makes it the division you were expecting.

The same symbol, three jobs, chosen by the operand types
ExpressionTypesWhat the symbol doesResult
5 + 3int, intAddition8
"5" + 3String, intConcatenation"53"
7 / 2int, intWhole-number division3
7 / 2.0int, doubleDivision3.5

The same rule covers the other arithmetic symbols. *, - and % (the remainder after division) give a whole number when both sides are whole numbers, and a decimal when either side is a double. The result type is decided before the calculation, never by what the answer turns out to be.

So when an expression produces something you did not expect, the first question is not what the operator does. It is what types you handed it, because that is what chose the operator's job.