Operators are where Java code starts computing instead of just storing. They look trivial — everyone knows what + does — yet three of the most common fresher bugs live here: integer division silently discarding decimals, == comparing the wrong thing on strings, and i++ inside a larger expression doing something unexpected. Master the rules on this page and those bugs never make it past your editor.
The operator families at a glance
| Category | Operators | Purpose |
|---|---|---|
| Arithmetic | + - * / % |
Math on numbers |
| Unary | + - ++ -- ! |
Sign, increment/decrement, negation |
| Relational | == != > < >= <= |
Comparisons producing boolean |
| Logical | && || ! |
Combining boolean conditions |
| Assignment | = += -= *= /= %= |
Storing and updating values |
| Ternary | ? : |
Inline if-else expression |
| Bitwise | & | ^ ~ |
Bit-level AND, OR, XOR, NOT |
| Shift | << >> >>> |
Moving bits left or right |
| Type | instanceof (cast) |
Type checks and conversions |
Every operator works on the data types you already know, and the results flow into the variables you declare. Let's take the families in the order you will actually meet them.
Arithmetic operators and the integer division trap
+, -, *, / and % behave as expected — with one enormous exception. When both operands are integers, / performs integer division and throws away the fraction:
public class ArithmeticDemo {
public static void main(String[] args) {
int total = 275, students = 4;
System.out.println(total / students); // 68 (not 68.75!)
System.out.println(total % students); // 3 (the remainder)
System.out.println(total / (double) students); // 68.75 — fixed with a cast
System.out.println(275 / 4.0); // 68.75 — or a double literal
// modulo in real life
int minutes = 135;
System.out.println(minutes / 60 + "h " + minutes % 60 + "m"); // 2h 15m
System.out.println(7 % 2 == 0 ? "even" : "odd"); // odd
}
}
Notice the fix: making either operand a double promotes the whole division to floating point. The modulo operator % gives the remainder — the standard tool for even/odd checks, wrapping indexes and splitting time units.
Common mistake: A common mistake beginners make is computing an average as
sum / countwith twointvariables and wondering why 68.75 became 68. Integer division truncates silently. Cast one operand todoublebefore dividing — after, and the damage is already done.
One more + behavior: with a String on either side, + becomes concatenation, and evaluation is left to right. "Score: " + 1 + 2 prints Score: 12, while "Score: " + (1 + 2) prints Score: 3. String-building details live in Java strings.
Unary operators: i++ vs ++i
++ and -- add or subtract 1. The pre/post distinction only matters when the expression's value is used:
public class IncrementDemo {
public static void main(String[] args) {
int i = 5;
int a = i++; // a = 5, then i becomes 6 (post: use, then change)
int b = ++i; // i becomes 7, then b = 7 (pre: change, then use)
System.out.println("a=" + a + " b=" + b + " i=" + i); // a=5 b=7 i=7
int x = 10;
x = x++; // the classic trap
System.out.println(x); // 10 — not 11!
}
}
That last line is a favorite written-test question. x++ returns the old value (10), then increments x to 11, and finally the assignment overwrites x with the returned 10. Rule for real code: keep ++/-- as standalone statements and this whole category of confusion disappears.
Relational operators and the == trap on objects
==, !=, <, >, <=, >= all produce a boolean. On primitives they do exactly what you expect. On objects, == compares references — whether two variables point at the same object — not contents:
String s1 = new String("java");
String s2 = new String("java");
System.out.println(s1 == s2); // false — different objects
System.out.println(s1.equals(s2)); // true — same characters
Burn this in: text comparison is always .equals() (or .equalsIgnoreCase()). The reason == sometimes appears to work on strings is the string pool, explained in Java strings — and relying on it is how intermittent bugs are born.
Interview note: "Difference between == and equals()" appears in nearly every fresher interview. Structure your answer in two halves — primitives vs references for
==, default vs overridden behavior forequals()— and mention that String, Integer and all collections rely on overriddenequals().
Logical operators and short-circuiting
&& (AND), || (OR) and ! (NOT) combine booleans — and the first two short-circuit: evaluation stops as soon as the answer is known.
public class ShortCircuitDemo {
static boolean isValid(String s) {
System.out.println(" isValid called");
return s.length() > 3;
}
public static void main(String[] args) {
String input = null;
// Safe: right side never runs when left is false
if (input != null && isValid(input)) {
System.out.println("valid");
} else {
System.out.println("invalid or null"); // no NullPointerException
}
// Order matters: swap the operands and this would crash
boolean ok = (input == null) || isValid(input);
System.out.println("ok = " + ok); // isValid never called
}
}
Short-circuiting is not an optimization detail — it is a guard pattern. x != null && x.something() is the standard null-safe idiom across every Java codebase. The single-character versions & and | also work on booleans but evaluate both sides unconditionally; in conditions you want && and || essentially always. These conditions feed directly into the if/else structures covered in Java control statements.
Assignment and compound assignment
Beyond plain =, the compound forms +=, -=, *=, /=, %= update a variable in place. total += marks reads as "add marks to total". One subtlety: compound assignment includes a hidden cast to the left-hand type, so byte b = 10; b += 3; compiles even though b = b + 3; does not (the + promotes to int). Handy trivia for written tests; in daily code, just know += is safe and concise — especially as the accumulator pattern inside loops.
The ternary operator
condition ? valueIfTrue : valueIfFalse is an expression form of if-else — it produces a value:
int marks = 67;
String result = marks >= 40 ? "PASS" : "FAIL";
double fee = isEarlyBird ? 20000.0 : 25000.0;
Use it for simple either-or assignments. The moment you nest ternaries or hide side effects in the branches, switch to a full if/else — readability beats cleverness in every code review you will ever face.
Bitwise and shift operators
Bitwise operators treat integers as raw bit patterns. You will use them rarely in business code, but they appear in interviews, in flag-based APIs and inside library source like HashMap:
public class BitwiseDemo {
public static void main(String[] args) {
int a = 12, b = 10; // 1100 and 1010 in binary
System.out.println(a & b); // 8 (1000) AND: both bits set
System.out.println(a | b); // 14 (1110) OR: either bit set
System.out.println(a ^ b); // 6 (0110) XOR: exactly one set
System.out.println(~a); // -13 NOT: flips every bit
System.out.println(a << 1); // 24 shift left = multiply by 2
System.out.println(a >> 2); // 3 shift right = divide by 4
System.out.println(-8 >>> 1);// 2147483644: unsigned shift fills with 0
System.out.println((a & 1) == 0 ? "even" : "odd"); // bit-level even check
}
}
The patterns worth remembering: x << n multiplies by 2^n, x >> n divides by 2^n (keeping the sign bit), and >>> shifts zeros in from the left regardless of sign — the difference between >> and >>> is a standard interview question. XOR's "exactly one" property powers classic puzzles like finding the unique number in an array of pairs.
Pro tip: You do not need bitwise fluency to start building projects — but recognize the symbols so
flags & MASKin framework code does not look like magic. Revisit this section before interviews; one confident bitwise answer separates you from candidates who skipped "the hard operators".
Precedence: who goes first
Java evaluates operators in a fixed priority order. The slice you need daily:
- Unary:
++ -- ! ~ - Multiplicative:
* / % - Additive:
+ - - Relational:
< > <= >= instanceof - Equality:
== != - Logical AND
&&, then logical OR|| - Ternary
? : - Assignment
= += ...(lowest)
So a + b * c multiplies first, and x > 0 && y > 0 || z > 0 groups as (x > 0 && y > 0) || (z > 0) — && binds tighter than ||.
Common mistake: A common mistake beginners make is writing long mixed conditions and trusting memorized precedence. When
&&and||share an expression, add parentheses even if they are redundant. The compiler does not need them; the human debugging your code at 6 PM does.
What to practice next
Write five tiny programs before moving on: a marks-to-grade converter (ternary + relational), an even/odd and leap-year checker (modulo + logical), a minutes-to-hours formatter (/ and %), a null-safe string length printer (short-circuit &&), and a bit-pattern printer using Integer.toBinaryString(). Each takes ten minutes, and together they cover every family above.
Then continue the series with Java control statements, where these operators start steering if, else and switch — the decision-making core of every program.
Frequently Asked Questions
What is the difference between == and equals() in Java?
What is the difference between ++i and i++?
What is the difference between && and & in Java?
What does the modulo operator % do in Java?
What is the ternary operator in Java?
Why does 5 / 2 give 2 instead of 2.5 in Java?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — Explore the Program

