Java Programming Operators Guide Study Guide

Java Operators - Complete Guide

Master all Java operators with detailed explanations, usage examples, and operator precedence rules. Operators are special symbols that perform operations on variables and values.

1. Introduction to Java Operators

Operators perform calculations, comparisons, and logical tests on operands. Java supports arithmetic, relational, logical, bitwise, assignment, and ternary operators.

  • Unary: ++, --, !
  • Binary: +, -, *, /, %
  • Relational: ==, !=, <, >, <=, >=
  • Logical: &&, ||, !
Arithmetic operators
public class OperatorIntro {
    public static void main(String[] args) {
        int a = 10, b = 3;
        System.out.println(a + b);
        System.out.println(a % b);
        System.out.println(a > b);
    }
}

2. Java Operators by Type

Each category below lists operators with their purpose and a short example. Use these tables as a quick reference while coding or preparing for interviews.

Arithmetic operators

Operator Purpose Short example
+Add two numeric values; also concatenates stringssum = a + b;
-Subtract right operand from leftdiff = a - b;
*Multiply two valuesprod = a * b;
/Divide left by right (integer division truncates)quot = 7 / 2;3
%Remainder after division (modulus)rem = 7 % 3;1

Unary operators

Operator Purpose Short example
++Increment by 1 (prefix: before use; postfix: after)count++; or ++count;
--Decrement by 1count--;
+ -Unary plus / minus on a single valueint n = -x;
!Logical NOT — flips boolean valueif (!active) { ... }

Relational (comparison) operators

Operator Purpose Short example
==True if operands are equalif (a == b) { ... }
!=True if operands are not equalif (x != 0) { ... }
< >Less than / greater thanif (age > 18) { ... }
<= >=Less than or equal / greater than or equalif (score >= 60) { ... }

Logical operators

Operator Purpose Short example
&&Logical AND — short-circuits if left is falseif (x > 0 && y > 0) { ... }
||Logical OR — short-circuits if left is trueif (isAdmin || isOwner) { ... }
!Negate a boolean conditionwhile (!done) { ... }

Bitwise operators

Operator Purpose Short example
&Bitwise AND — each bit comparedint mask = a & 0xFF;
|Bitwise OR — set bits where either operand has 1flags |= PERM_READ;
^Bitwise XOR — 1 where bits differtoggle = x ^ 1;
~Bitwise complement (flip all bits)int inv = ~n;
<<Left shift — multiply by powers of 2int x = 1 << 3;8
>>Signed right shift (sign bit preserved)int y = 16 >> 2;4
>>>Unsigned right shift (zero-fill left)int z = -1 >>> 1;

Assignment operators

Operator Purpose Short example
=Assign value to variablex = 10;
+=Add and assigntotal += price;
-=Subtract and assignbalance -= fee;
*= /= %=Multiply, divide, or modulus then assigncount *= 2;
&= |= ^= <<= >>= >>>=Bitwise compound assignmentflags |= MASK;

Ternary and other operators

Operator Purpose Short example
? :Conditional — pick one of two valuesmax = (a > b) ? a : b;
instanceofTest whether an object is of a typeif (obj instanceof String) { ... }

3. How Bitwise Operators Work (Positive & Negative)

Bitwise operators (&, |, ^, ~, <<, >>, >>>) work on the binary bits of int, long, byte, and short. In Java, signed integers use two's complement to represent negative numbers.

Positive numbers in binary

Non-negative values use normal binary: each bit is a power of two. Example with 8 bits (for clarity; int uses 32 bits):

+5 = 0000 0101 ↑ ↑ 4 1 → 4 + 1 = 5 +12 = 0000 1100 → 8 + 4 = 12

Negative numbers — two's complement

To store -n: flip all bits of +n (one's complement), then add 1. Equivalently in Java: -n == ~n + 1 (for the same type).

+5 = 0000 0101 Flip: 1111 1010 Add 1: 1111 1011 → this bit pattern is -5 Check: ~5 + 1 → in Java, ~5 flips all 32 bits, then +1 gives -5
Decimal (8-bit view) Binary Notes
+50000 0101Positive — leading bit 0
-51111 1011Negative — leading bit 1 in two's complement
-11111 1111All bits set (for 8 bits)
-1281000 0000Smallest 8-bit signed value

Bitwise AND (&) — positive and negative

Result bit is 1 only if both operands have 1 in that position.

Positive: 12 & 10 12 = 0000 1100 10 = 0000 1010 -------- 0000 1000 = 8 Negative: -5 & -3 (8-bit view) -5 = 1111 1011 -3 = 1111 1101 -------- 1111 1001 = -7

Common use: value & 0xFF keeps the lowest 8 bits (works the same whether the high bits are 0 or 1).

Bitwise OR (|) and XOR (^)

OR: 1 where either operand has 1 12 | 10 = 0000 1100 | 0000 1010 = 0000 1110 = 14 XOR: 1 where bits differ (same → 0) 12 ^ 10 = 0000 1100 ^ 0000 1010 = 0000 0110 = 6 -5 ^ -3 = 1111 1011 ^ 1111 1101 = 0000 0110 = 6

Bitwise NOT (~)

Flips every bit. For signed integers, ~n == -(n + 1).

~5 → all bits of 5 flipped → -6 ~(-5) → flips -5's pattern → +4 Example: ~0 on int = -1 (all 32 bits were 0, all become 1 → -1)

Left shift (<<) — positive and negative

Shifts bits left; vacated right bits are filled with 0. For non-negative values, n << k is like multiplying by 2^k (until overflow).

5 << 2 = 0000 0101 << 2 = 0001 0100 = 20 (5 × 4) -5 << 1 (8-bit view): 1111 1011 → 1111 0110 = -10 (Watch overflow on real int — shifting into sign bit can change sign unexpectedly.)

Right shift — signed (>>) vs unsigned (>>>)

This is where positive and negative behave differently.

Operator Left vacated bits Typical use
>>Copy the sign bit (arithmetic shift)Signed int — preserves sign
>>>Fill with 0 (logical shift)Treat bits as unsigned; clear high bits
Positive: 20 >> 2 0001 0100 >> 2 = 0000 0101 = 5 (20 ÷ 4) Negative: -8 >> 1 (8-bit view) 1000 0000 >> 1 = 1100 0000 = -4 (sign bit 1 copied in) -1 >> 1 → still -1 on int (all 1s shift right, sign stays 1) -1 >>> 1 → large positive (2147483647 on 32-bit int) High bits become 0 — treats pattern as unsigned

Remember

>> keeps the number “looking” negative when it started negative. >>> does not — use it when you want to zero-fill the left, e.g. extracting an unsigned byte from an int: (byteVal & 0xFF) or intVal >>> 8.

Bitwise demo — positive and negative
public class BitwiseSignedDemo {
    public static void main(String[] args) {
        int a = 12, b = 10;
        System.out.println("12 & 10 = " + (a & b));   // 8
        System.out.println("12 | 10 = " + (a | b));   // 14
        System.out.println("12 ^ 10 = " + (a ^ b));   // 6

        int n = 5;
        System.out.println("~5 = " + (~n));           // -6
        System.out.println("5 << 2 = " + (n << 2));     // 20

        int neg = -8;
        System.out.println("-8 >> 1 = " + (neg >> 1));   // -4
        System.out.println("-8 >>> 1 = " + (neg >>> 1)); // 2147483644

        int mask = -1;
        System.out.println("-1 >> 1 = " + (mask >> 1));   // -1
        System.out.println("-1 >>> 1 = " + (mask >>> 1)); // 2147483647

        // Two's complement check
        System.out.println("-5 in binary (32-bit): " + Integer.toBinaryString(-5));
        System.out.println("~5 + 1 = " + ((~5) + 1)); // -5
    }
}

4. Operator Precedence and Associativity

When multiple operators appear in one expression, precedence determines evaluation order. Use parentheses to make intent explicit and avoid subtle bugs.

  • Multiplication before addition
  • Relational before logical AND
  • Assignment has low precedence
  • Most operators associate left-to-right
Precedence example
public class PrecedenceDemo {
    public static void main(String[] args) {
        int result = 2 + 3 * 4;
        System.out.println(result);
        System.out.println((2 + 3) * 4);
    }
}

5. Operator Examples

Short-circuit logical operators (&& and ||) skip the right operand when the result is already determined. This prevents null pointer errors in chained conditions.

  • Use && instead of & for boolean logic
  • Prefix ++i increments before use
  • Compound assignment: x += 5
  • String + concatenates text
Logical short-circuit
public class LogicDemo {
    public static void main(String[] args) {
        String name = null;
        if (name != null && name.length() > 0) {
            System.out.println(name);
        } else {
            System.out.println("No name");
        }
    }
}

6. Operators Best Practices

Clear expressions reduce bugs in interviews and production code. Prefer readability over clever one-liners.

  • Use parentheses for complex expressions
  • Avoid mixing ++ with other operators in one line
  • Compare strings with equals(), not ==
  • Use Math methods for advanced math
  • Watch integer division truncation

7. Tricky Points

Common operator pitfalls in Java interviews and real code — grouped by operator type.

Arithmetic

Integer division: 7 / 2 is 3, not 3.5. Cast at least one operand: 7.0 / 2 or (double) 7 / 2.
Modulus sign: -7 % 3 is -1 in Java (sign of dividend), not 2.
String + number: "Score: " + 5 + 10 prints Score: 510 because + is left-associative string concatenation after the first +.

Unary and increment

Prefix vs postfix: int x = 5; int y = x++; leaves x == 6 and y == 5. With ++x, both become 6 before assignment.
Confusing lines: Avoid a[i++] = i; — evaluation order is hard to read and easy to get wrong.

Relational and logical

= vs ==: if (x = 5) assigns; if (x == 5) compares. A common typo in C-style languages.
Strings and ==: "a" == "a" may be true (pool), but new String("a") == new String("a") is false. Use equals().
Short-circuit: In obj != null && obj.length() > 0, length() is never called if obj is null. With & (bitwise AND on booleans), both sides always run — risk of NullPointerException.

Bitwise

& vs &&: & is bitwise AND (or non-short-circuit boolean AND). && is logical AND with short-circuit — use && in conditions.
Shift limits: Only the lowest 5 bits of the shift count are used for int (shift by 32 is same as shift by 0).

Assignment, ternary, and precedence

Compound assignment: a += b * c means a = a + (b * c), not (a + b) * c.
Ternary nesting: a > b ? x : c > d ? y : z is legal but hard to read — use parentheses or if-else.
Precedence: 2 + 3 * 4 is 14, not 20. When in doubt, add parentheses.

Rule of thumb

Use parentheses for clarity; equals() for strings; && / || for conditions; cast for real division; avoid clever ++ in the same expression as other uses of the variable.