Operators and expressions
Java's operators, grouped:
- Arithmetic:
+ - * / %. Integer division drops the fraction, so7 / 2is 3 and7 % 2(the remainder) is 1. - Increment:
i++uses the value and then adds one;++iadds first. - Compound assignment:
+=,-=,*=. They also cast back to the variable's type. - Comparison:
== != < > <= >=produce aboolean. - Logical:
&&and||short-circuit, so the right side runs only when needed;!negates. - Ternary:
condition ? a : bpicks one of two values.
Precedence: * / % before + -, comparisons before &&, and && before ||. When in doubt, add parentheses.
Mixing types promotes to the wider type, so int + double gives a double. Going narrower needs a cast: (int) 3.9 is 3.
Example
int a = 7, b = 2;
System.out.println(a / b); // 3 (integer division)
System.out.println(a % b); // 1 (remainder)
System.out.println(a / 2.0); // 3.5 (double division)
int i = 5;
int x = i++; // x = 5, then i becomes 6
int y = ++i; // i becomes 7, then y = 7
String user = null;
if (user != null && user.length() > 3) { // && stops before calling length()
System.out.println("valid");
}
int marks = 72;
String result = marks >= 40 ? "Pass" : "Fail";
int rounded = (int) 3.99; // 3: casting truncates
long big = 1_000_000L * 3_000; // long avoids int overflowCommon mistake
Writing if (done = true) instead of if (done == true). With booleans it compiles, assigns true, and the branch always runs. Just write if (done).
Under the hood
& and | on booleans don't short-circuit, so both sides always run. Bitwise operators (& | ^ ~ << >> >>>) work on the bits of integers and appear in flags, hashing and performance code; >>> shifts in zeros while >> keeps the sign. Floating-point maths is approximate: 0.1 + 0.2 is 0.30000000000000004, which is why money uses BigDecimal.
Check yourself
What does 9 / 2 * 2 evaluate to in Java?
How this connects
Know these first
Part of Java from zero.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.