Working with Operators and Expressions

1. Using Arithmetic Operators (+, -, *, /, %)

OperatorDescriptionNotes
+Addition / String concatPromotes to wider type
-Subtraction
*MultiplicationMay overflow silently
/DivisionInteger / integer truncates
%ModulusSign matches dividend
Warning: int / 0 throws ArithmeticException; double / 0 yields Infinity or NaN.

2. Using Unary Operators (++, --, +, -, !)

OperatorPositionEffect
++xPrefixIncrement, returns new value
x++PostfixReturns old value, then increments
--x / x--Pre/PostDecrement
+ / -PrefixSign
!PrefixLogical NOT (boolean only)
~PrefixBitwise complement

3. Using Relational Operators (==, !=, >, <, >=, <=)

OperatorUse
==Equal (reference equality for objects)
!=Not equal
> < >= <=Numeric comparison only
Warning: Use .equals() for object value comparison; == compares references.

4. Using Logical Operators (&&, ||, !)

OperatorDescriptionShort-Circuit
&&Logical ANDYes
||Logical ORYes
!Logical NOT
& |Boolean AND/OR (no short-circuit)No
^Boolean XORNo

5. Using Bitwise Operators (&, |, ^, ~, <<, >>, >>>)

OperatorActionExample
&AND0b1100 & 0b1010 = 0b1000
|OR0b1100 | 0b1010 = 0b1110
^XOR0b1100 ^ 0b1010 = 0b0110
~NOT~5 = -6
<<Left shift1 << 3 = 8
>>Signed right shiftPreserves sign bit
>>>Unsigned right shiftFills with 0

6. Using Assignment Operators (=, +=, -=, *=, /=)

OperatorEquivalent
x += yx = (T)(x + y) (implicit cast)
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
&= |= ^= <<= >>= >>>=Compound bitwise

7. Using Ternary Operator (? :)

Example: Ternary

String label = (count == 1) ? "item" : "items";
int max = (a > b) ? a : b;
String status = user.isActive() ? "online" : user.isAway() ? "away" : "offline";
AspectDetail
Syntaxcondition ? exprIfTrue : exprIfFalse
Result typeCommon supertype of both branches

8. Understanding Operator Precedence

PrecedenceOperators
1 (highest)() [] . postfix ++ --
2prefix ++ -- + - ! ~ (cast)
3* / %
4+ -
5<< >> >>>
6< > <= >= instanceof
7== !=
8-10&, ^, |
11-12&&, ||
13?:
14 (lowest)= += -= *= ...

9. Using instanceof Operator

Example: Pattern matching for instanceof JAVA 16+

Object obj = "hello";
if (obj instanceof String s) {
    System.out.println(s.length());   // s is auto-cast
}
FormBehavior
x instanceof Ttrue if x is non-null T or subtype
x instanceof T tPattern variable binding (Java 16+)
null instanceof TAlways false

10. Understanding Short-Circuit Evaluation

OperatorStops When
&&Left side is false
||Left side is true

Example: Null-safe check

if (user != null && user.isActive()) { ... }   // safe
if (cache != null || (cache = loadCache()) != null) { ... }