Java Operators — Arithmetic, Relational, Logical & More

6 minute read

Operators are symbols that tell the compiler to perform a specific operation on one, two, or three operands. Java has a rich set of operators — and understanding them is essential for writing any meaningful program.


What Is an Operator?

An operator is a symbol that performs an operation on operands and produces a result.

int result = 10 + 5;  // + is the operator, 10 and 5 are operands

Java operators fall into several categories:

Category Examples
Arithmetic +, -, *, /, %
Relational ==, !=, <, >, <=, >=
Logical &&, \|\|, !
Bitwise &, \|, ^, ~, <<, >>, >>>
Assignment =, +=, -=, *=, /=, %=
Unary +, -, ++, --, !
Ternary ? :
Special instanceof

Arithmetic Operators

These perform basic math operations.

int a = 20, b = 7;

System.out.println(a + b);   // 27  — addition
System.out.println(a - b);   // 13  — subtraction
System.out.println(a * b);   // 140 — multiplication
System.out.println(a / b);   // 2   — integer division (truncated)
System.out.println(a % b);   // 6   — modulus (remainder)

Integer Division vs Floating-Point Division

System.out.println(7 / 2);     // 3   — integer division
System.out.println(7.0 / 2);   // 3.5 — floating-point division
System.out.println(7 / 2.0);   // 3.5 — one operand is double

Rule: If both operands are integers, Java performs integer division (truncates the decimal). If either operand is a floating-point type, the result is floating-point.

The Modulus Operator %

The modulus operator returns the remainder after division.

System.out.println(10 % 3);   // 1
System.out.println(15 % 5);   // 0
System.out.println(-7 % 3);   // -1  (sign follows dividend)

Common uses:

  • Check even/odd: n % 2 == 0 means even
  • Wrap around: index % arrayLength
  • Extract digits: n % 10 gives the last digit

Unary Operators

These operate on a single operand.

int x = 5;

System.out.println(+x);   // 5   — unary plus (rarely used)
System.out.println(-x);   // -5  — unary minus (negation)
System.out.println(!true); // false — logical NOT

Increment and Decrement

int a = 10;

// Post-increment: use current value, THEN increment
System.out.println(a++);  // prints 10, then a becomes 11

// Pre-increment: increment FIRST, then use value
System.out.println(++a);  // a becomes 12, prints 12

// Post-decrement
System.out.println(a--);  // prints 12, then a becomes 11

// Pre-decrement
System.out.println(--a);  // a becomes 10, prints 10

Key difference:

  • a++ — use, then increment
  • ++a — increment, then use

Common Pitfall

int i = 5;
int result = i++ + ++i;
// i++ gives 5 (then i becomes 6)
// ++i makes i 7 (then gives 7)
// result = 5 + 7 = 12

⚠️ Avoid using multiple ++/-- on the same variable in one expression. It makes code confusing.


Relational (Comparison) Operators

These compare two values and return a boolean.

int a = 10, b = 20;

System.out.println(a == b);  // false — equal to
System.out.println(a != b);  // true  — not equal to
System.out.println(a < b);   // true  — less than
System.out.println(a > b);   // false — greater than
System.out.println(a <= b);  // true  — less than or equal
System.out.println(a >= b);  // false — greater than or equal

== vs .equals()

String s1 = new String("hello");
String s2 = new String("hello");

System.out.println(s1 == s2);      // false — compares references
System.out.println(s1.equals(s2)); // true  — compares content

Rule: Use == for primitives and .equals() for objects.


Logical Operators

These combine boolean expressions.

boolean a = true, b = false;

System.out.println(a && b);  // false — AND (both must be true)
System.out.println(a || b);  // true  — OR (at least one true)
System.out.println(!a);      // false — NOT (inverts)

Short-Circuit Evaluation

Java uses short-circuit evaluation:

// && stops at first false
if (false && expensiveMethod()) {
    // expensiveMethod() is NEVER called
}

// || stops at first true
if (true || expensiveMethod()) {
    // expensiveMethod() is NEVER called
}

This is useful for null checks:

if (name != null && name.length() > 0) {
    // safe — if name is null, length() is never called
}

Bitwise vs Logical

// & and | do NOT short-circuit
if (false & expensiveMethod()) {
    // expensiveMethod() IS called even though left is false
}

Use && and || in conditions. Use & and | only for bitwise operations.


Assignment Operators

The basic assignment operator is =. Java also has compound assignment operators.

int x = 10;

x += 5;   // x = x + 5  → 15
x -= 3;   // x = x - 3  → 12
x *= 2;   // x = x * 2  → 24
x /= 4;   // x = x / 4  → 6
x %= 4;   // x = x % 4  → 2

Compound Assignment and Casting

Compound assignment operators include an implicit cast:

byte b = 10;
b += 5;       // OK — equivalent to b = (byte)(b + 5)
// b = b + 5; // ERROR — b + 5 is int, can't assign to byte

Bitwise Operators

These operate on individual bits of integer types.

int a = 5;  // binary: 0101
int b = 3;  // binary: 0011

System.out.println(a & b);   // 1  (0001) — AND
System.out.println(a | b);   // 7  (0111) — OR
System.out.println(a ^ b);   // 6  (0110) — XOR
System.out.println(~a);      // -6        — NOT (inverts all bits)

Shift Operators

int x = 8;  // binary: 1000

System.out.println(x << 2);   // 32  — left shift (multiply by 2²)
System.out.println(x >> 2);   // 2   — right shift (divide by 2²)
System.out.println(x >>> 2);  // 2   — unsigned right shift

Practical uses:

  • Multiply by power of 2: n << k = n × 2ᵏ
  • Divide by power of 2: n >> k = n ÷ 2ᵏ
  • Check if bit is set: (n & (1 << k)) != 0

Ternary Operator

The ternary operator is a shorthand if-else.

// Syntax: condition ? valueIfTrue : valueIfFalse

int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status);  // Adult
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println(max);  // 20

Use the ternary operator for simple one-line decisions. For complex logic, use if-else.


The instanceof Operator

Checks if an object is an instance of a specific class or interface.

String text = "hello";
System.out.println(text instanceof String);  // true
System.out.println(text instanceof Object);  // true

Object obj = null;
System.out.println(obj instanceof String);   // false (null is never an instanceof)

Since Java 16, you can combine instanceof with pattern matching:

Object obj = "Hello";
if (obj instanceof String s) {
    System.out.println(s.toUpperCase());  // HELLO
}

Operator Precedence

When multiple operators appear in one expression, Java follows a precedence order.

Priority Operators Direction
1 (highest) () Left to right
2 ++ -- (postfix) Left to right
3 ++ -- (prefix) + - ! ~ Right to left
4 * / % Left to right
5 + - Left to right
6 << >> >>> Left to right
7 < <= > >= instanceof Left to right
8 == != Left to right
9 & Left to right
10 ^ Left to right
11 \| Left to right
12 && Left to right
13 \|\| Left to right
14 ? : Right to left
15 (lowest) = += -= etc. Right to left

When in Doubt, Use Parentheses

// Hard to read
int result = 2 + 3 * 4;  // 14, not 20

// Clear
int result = 2 + (3 * 4);  // 14 — explicit

Best practice: Don’t rely on memorizing the table. Use parentheses to make intent clear.


Quick Exercises

  1. What does 10 % 3 + 2 * 4 evaluate to?
  2. What’s the difference between ++x and x++ when used inside System.out.println()?
  3. Write a one-liner using the ternary operator to print “Even” or “Odd” for a number.
  4. What does true || false && false evaluate to? (Hint: && has higher precedence than ||.)

Summary

Operator Type Purpose
Arithmetic Math operations
Unary Increment, decrement, negation
Relational Compare values → boolean
Logical Combine boolean expressions
Assignment Assign and compound-assign values
Bitwise Bit-level operations
Ternary Inline if-else
instanceof Type checking

What’s Next?

Now that you can perform operations on data, let’s learn how to display output using System.out.println() and its variations — in the next chapter: Print Output.

Updated: