iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Operators

Operators in Java fall into arithmetic, comparison, logical, bitwise, and assignment groups. The trap-free ones look like every C-family language; == on objects compares references (use .equals() for value).

The traps you keep meeting

EXAMPLE
// Arithmetic
int a = 17, b = 5;
System.out.println(a / b);   // 3   (integer division, truncated)
System.out.println(a % b);   // 2
System.out.println(a / (double) b);   // 3.4

// Integer overflow wraps silently
int big = Integer.MAX_VALUE;
System.out.println(big + 1);   // -2147483648 — wraps!
System.out.println(Math.addExact(big, 1));   // throws ArithmeticException

// Short-circuit logical operators
if (user != null && user.isAdmin()) ...   // safe — never NPEs
if (user != null & user.isAdmin())  ...   // BAD — both sides evaluated

// == on objects is reference equality
String a1 = new String("hi");
String a2 = new String("hi");
System.out.println(a1 == a2);         // false — different instances
System.out.println(a1.equals(a2));    // true

// String literals come from a pool — same reference
String l1 = "hi", l2 = "hi";
System.out.println(l1 == l2);         // true — but DON'T rely on this

// Ternary
int n = -3;
String sign = n > 0 ? "+" : n < 0 ? "-" : "0";

// Bitwise (occasionally useful)
int mask = 0b0101;
System.out.println(mask & 0b0110);   // 4 → 0b0100
System.out.println(mask | 0b0010);   // 7 → 0b0111
System.out.println(1 << 4);          // 16

Why it matters

For money, use BigDecimal with the explicit operators (add, multiply) and a RoundingMode. Doubles can’t represent 0.1; cents go missing.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
int x = 7, y = 3;
System.out.println(x + y);  // 10
System.out.println(x / y);  // 2  (integer)
System.out.println(x % y);  // 1
Try it Yourself »

Discussion

Loading…