Card 01/ 09
All 9 cards
ConceptDifficulty: Beginner1 min
One Symbol, Several Jobs: What the Types Decide
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.
System.out.println(5 + 3);
System.out.println("5" + 3);8
53The compiler reads the types of both operands and then decides what the symbol means. Two numbers make + addition. One string makes it concatenation, 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.
| Expression | Types | What the symbol does | Result |
|---|---|---|---|
5 + 3 | int, int | Addition | 8 |
"5" + 3 | String, int | Concatenation | "53" |
7 / 2 | int, int | Whole-number division | 3 |
7 / 2.0 | int, double | Division | 3.5 |
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.