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 compareStringcontent — use.equals()instead. (String literals like"hi" == "hi"often happen to returntruedue to an internal optimization called string interning, but relying on that is a bug waiting to happen.) - Forgetting integer division truncates:
7 / 2is3, not3.5.