Skip to content
AgileLogics
4 min read

Operators

Prerequisites: Type casting & conversion

Java supports the usual arithmetic (+ - * / % ++ --), comparison (== != > < >= <=), and logical (&& || !) operators.

int a = 7, b = 2;
System.out.println(a / b);   // 3 — integer division truncates
System.out.println(a % b);   // 1 — remainder
System.out.println((double) a / b); // 3.5 — cast one side first

For objects (including String), == compares references (whether two variables point to the exact same object in memory), not their contents:

String a = new String("hi");
String b = new String("hi");
System.out.println(a == b);        // false — different objects
System.out.println(a.equals(b));   // true — same content

Common mistakes

  • Using == to compare String content — use .equals() instead. (String literals like "hi" == "hi" often happen to return true due to an internal optimization called string interning, but relying on that is a bug waiting to happen.)
  • Forgetting integer division truncates: 7 / 2 is 3, not 3.5.