JavaBasicsbeginner
Updated:

Java Operators: Arithmetic, Logical, Bitwise and More

7 min read

Every Java operator category explained with runnable examples — from integer division surprises to short-circuit logic, i++ vs ++i, and bit shifting.

TL;DR – Quick Answer

Java operators are symbols that perform operations on variables and values. The main categories are arithmetic (+ - * / %), relational (== != < >), logical (&& || !), assignment (= += -=), unary (++ -- !), ternary (?:) and bitwise (& | ^ << >>). The ones that surprise beginners most are integer division, which drops the decimal part, and == on objects, which compares references instead of contents.

On This Page

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 / count with two int variables and wondering why 68.75 became 68. Integer division truncates silently. Cast one operand to double before 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 for equals() — and mention that String, Integer and all collections rely on overridden equals().

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 & MASK in 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:

  1. Unary: ++ -- ! ~
  2. Multiplicative: * / %
  3. Additive: + -
  4. Relational: < > <= >= instanceof
  5. Equality: == !=
  6. Logical AND &&, then logical OR ||
  7. Ternary ? :
  8. 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?
== compares primitive values directly, but on objects it compares references — whether both variables point to the same object. equals() compares logical content when a class overrides it, as String and Integer do. For comparing text, always use equals(), never ==.
What is the difference between ++i and i++?
Both increment i by 1. Pre-increment (++i) increments first and the expression evaluates to the new value; post-increment (i++) evaluates to the old value and then increments. Standing alone in a statement, they behave identically.
What is the difference between && and & in Java?
&& is the logical AND that short-circuits: if the left side is false, the right side is never evaluated. & on booleans evaluates both sides always, and on integers it performs bitwise AND. In conditions you almost always want && for safety and performance.
What does the modulo operator % do in Java?
It returns the remainder of a division: 17 % 5 is 2. It is used for even or odd checks, cycling through ranges, and extracting digits. With negative operands, the result takes the sign of the left operand, so -7 % 3 is -1.
What is the ternary operator in Java?
It is the compact conditional condition ? valueIfTrue : valueIfFalse, the only operator taking three operands. For example, String result = marks >= 40 ? "PASS" : "FAIL". Use it for simple either-or assignments and switch to if-else when logic nests or has side effects.
Why does 5 / 2 give 2 instead of 2.5 in Java?
When both operands are integers, Java performs integer division and truncates the fraction. To get 2.5, make at least one operand a double: 5 / 2.0 or 5.0 / 2. This single rule causes a large share of wrong-average bugs in beginner code.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Explore the Program

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 14 July 2026 LinkedIn
Chat with us