Foundation
03 — Operators & Casting
Previous: 02 Variables & Types · Next: 04 Control Flow
▶️ java pkg1core/core4Operators.java
Arithmetic operators
| Operator | Meaning | Example |
|---|---|---|
+ - * |
Add, subtract, multiply | 5 + 3 → 8 |
/ |
Division | 7 / 2 → 3 (integer division!) |
% |
Remainder (modulo) | 7 % 2 → 1 |
1int a = 7, b = 2;2System.out.println(a / b); // 3 (not 3.5)3System.out.println(a % b); // 14System.out.println(7 / 2.0); // 3.5 (double division)⚠️ Integer division truncates — 7 / 2 is 3, not 3.5.
Assignment & compound operators
1int x = 10;2x += 5; // x = x + 5 → 153x *= 2; // x = x * 2 → 304x++; // post-increment: use then add 15++x; // pre-increment: add 1 then useComparison operators
Return boolean: == != < > <= >=
1int i = 0;2System.out.println(i++ + ++i); // 0 + 2 = 2 (tricky — trace on paper!)💡 Use == for primitives; use .equals() for objects (especially String).
Logical operators
| Operator | Meaning |
|---|---|
&& |
AND (short-circuit) |
|| |
OR (short-circuit) |
! |
NOT |
Short-circuit: false && anything never evaluates anything.
1if (list != null && !list.isEmpty()) { ... } // safe — null check firstBitwise operators
| & ^ ~ << >> >>> — operate on individual bits. Used in flags, permissions, low-level math.
1System.out.println(5 & 3); // 1 (0101 & 0011 = 0001)2System.out.println(5 | 3); // 73System.out.println(~1); // -2 (two's complement)Ternary operator
1String grade = (score >= 60) ? "Pass" : "Fail";Shorthand for simple if/else assignment.
Operator precedence (highest first)
()grouping++--!~*/%+-<><=>===!=&&||?:ternary=assignment
When in doubt, use parentheses.
Casting recap
| Cast | Name | Safe? |
|---|---|---|
int → long |
Widening | Automatic |
long → int |
Narrowing | Manual (int)x; may truncate |
double → int |
Narrowing | Truncates decimal part |
Practice
- Run
core4Operators. - Predict output of
i++ + ++ibefore running. - Write a ternary that picks the larger of two ints.
Next → 04 Control Flow Related → 01 Core Java
Source named in this chapter
- core4Operatorspkg1core/core4Operators.java