Skip to content
beginnerPhase 9 · Java Foundations

Operators

Master arithmetic, relational, logical, bitwise, and assignment operators.

45m
3 problems
Topic Progress0%

Arithmetic Operators

Arithmetic Operators

public class Arithmetic {
    public static void main(String[] args) {
        int a = 10, b = 3;
        
        // Addition
        int sum = a + b;  // 13
        
        // Subtraction
        int diff = a - b;  // 7
        
        // Multiplication
        int product = a * b;  // 30
        
        // Division
        int quotient = a / b;  // 3 (integer division!)
        double precise = (double) a / b;  // 3.333...
        
        // Modulus (remainder)
        int remainder = a % b;  // 1
        
        System.out.println("Sum: " + sum);  // 13
        System.out.println("Diff: " + diff);  // 7
        System.out.println("Product: " + product);  // 30
        System.out.println("Quotient: " + quotient);  // 3
        System.out.println("Precise: " + precise);  // 3.333...
        System.out.println("Remainder: " + remainder);  // 1
    }
}

Increment/Decrement

public class IncrementDecrement {
    public static void main(String[] args) {
        int x = 5;
        
        // Post-increment: use then increment
        int a = x++;  // a = 5, x = 6
        System.out.println("a=" + a + ", x=" + x);  // a=5, x=6
        
        // Pre-increment: increment then use
        int b = ++x;  // x = 7, b = 7
        System.out.println("b=" + b + ", x=" + x);  // b=7, x=7
        
        // Post-decrement
        int c = x--;  // c = 7, x = 6
        System.out.println("c=" + c + ", x=" + x);  // c=7, x=6
        
        // Pre-decrement
        int d = --x;  // x = 5, d = 5
        System.out.println("d=" + d + ", x=" + x);  // d=5, x=5
    }
}

Integer Division Pitfall

// Integer division truncates!
int a = 7 / 2;  // 3 (not 3.5)
int b = -7 / 2;  // -3 (not -3.5)

// To get decimal result, cast to double
double c = (double) 7 / 2;  // 3.5
double d = 7.0 / 2;  // 3.5

// Modulus with negative numbers
int e = -7 % 2;  // -1 (sign follows dividend)
int f = 7 % -2;  // 1

Relational Operators

Relational (Comparison) Operators

public class Relational {
    public static void main(String[] args) {
        int a = 10, b = 20;
        
        // Equal to
        boolean eq = (a == b);  // false
        
        // Not equal to
        boolean neq = (a != b);  // true
        
        // Greater than
        boolean gt = (a > b);  // false
        
        // Less than
        boolean lt = (a < b);  // true
        
        // Greater than or equal
        boolean gte = (a >= b);  // false
        
        // Less than or equal
        boolean lte = (a <= b);  // true
        
        System.out.println("a == b: " + eq);  // false
        System.out.println("a != b: " + neq);  // true
        System.out.println("a > b: " + gt);   // false
        System.out.println("a < b: " + lt);   // true
        System.out.println("a >= b: " + gte);  // false
        System.out.println("a <= b: " + lte);  // true
    }
}

Comparing Objects

// NEVER use == to compare objects!
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2);      // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)

// Arrays
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
System.out.println(arr1 == arr2);      // false (different arrays)
System.out.println(Arrays.equals(arr1, arr2));  // true (same content)

// Enums (can use ==)
Color c1 = Color.RED;
Color c2 = Color.RED;
System.out.println(c1 == c2);  // true (same enum constant)

Chained Comparisons

// Java doesn't support chained comparisons like Python
// int x = 5;
// boolean valid = 0 < x < 10;  // COMPILE ERROR!

// Correct way
boolean valid = (x > 0) && (x < 10);  // true

// Range check method
public static boolean inRange(int value, int min, int max) {
    return value >= min && value <= max;
}

Logical Operators

Logical Operators

public class Logical {
    public static void main(String[] args) {
        boolean a = true, b = false;
        
        // Logical AND (both must be true)
        boolean and = a && b;  // false
        
        // Logical OR (at least one must be true)
        boolean or = a || b;  // true
        
        // Logical NOT (reverses)
        boolean not = !a;  // false
        
        System.out.println("AND: " + and);  // false
        System.out.println("OR: " + or);   // true
        System.out.println("NOT: " + not);  // false
    }
}

Short-Circuit Evaluation

// && and || use short-circuit evaluation
// If first operand determines result, second is not evaluated

public class ShortCircuit {
    public static void main(String[] args) {
        int x = 0;
        
        // Short-circuit AND: if first is false, skip second
        boolean result1 = (x != 0) && (10 / x > 2);
        // x != 0 is false, so 10 / x is never evaluated (no division by zero!)
        System.out.println("Result1: " + result1);  // false
        
        // Short-circuit OR: if first is true, skip second
        boolean result2 = (x == 0) || (10 / x > 2);
        // x == 0 is true, so 10 / x is never evaluated
        System.out.println("Result2: " + result2);  // true
        
        // Without short-circuit (bitwise & and |)
        // These evaluate BOTH operands
        // boolean dangerous = (x != 0) & (10 / x > 2);  // Division by zero!
    }
}

Truth Tables

AND (&&):
true  && true  = true
true  && false = false
false && true  = false
false && false = false

OR (||):
true  || true  = true
true  || false = true
false || true  = true
false || false = false

NOT (!):
!true  = false
!false = true

Bitwise Operators

Bitwise Operators

public class Bitwise {
    public static void main(String[] args) {
        int a = 12;  // binary: 1100
        int b = 10;  // binary: 1010
        
        // AND (&): both bits must be 1
        int and = a & b;  // 8 (binary: 1000)
        
        // OR (|): at least one bit must be 1
        int or = a | b;  // 14 (binary: 1110)
        
        // XOR (^): bits must differ
        int xor = a ^ b;  // 6 (binary: 0110)
        
        // NOT (~): flips all bits
        int not = ~a;  // -13 (two's complement)
        
        System.out.println("AND: " + and);  // 8
        System.out.println("OR: " + or);    // 14
        System.out.println("XOR: " + xor);  // 6
        System.out.println("NOT: " + not);  // -13
    }
}

Shift Operators

public class Shift {
    public static void main(String[] args) {
        int x = 8;  // binary: 1000
        
        // Left shift (<<): multiply by 2
        int left = x << 1;  // 16 (binary: 10000)
        int left2 = x << 3;  // 64 (binary: 1000000)
        
        // Right shift (>>): divide by 2 (signed)
        int right = x >> 1;  // 4 (binary: 100)
        
        // Unsigned right shift (>>>): divide by 2 (unsigned)
        int negative = -8;  // binary: 11111111111111111111111111111000
        int unsigned = negative >>> 1;  // 2147483644
        
        System.out.println("Left shift: " + left);  // 16
        System.out.println("Right shift: " + right);  // 4
        System.out.println("Unsigned shift: " + unsigned);  // 2147483644
    }
}

Bitwise Tricks

// Check if number is even/odd
boolean isEven = (num & 1) == 0;

// Swap without temp variable
a = a ^ b;
b = a ^ b;
a = a ^ b;

// Check if power of 2
boolean isPowerOf2 = (n > 0) && ((n & (n - 1)) == 0);

// Set bit at position i
num |= (1 << i);

// Clear bit at position i
num &= ~(1 << i);

// Toggle bit at position i
num ^= (1 << i);

// Check if bit at position i is set
boolean isSet = (num & (1 << i)) != 0;

Ternary Operator

Ternary Operator

public class Ternary {
    public static void main(String[] args) {
        int age = 20;
        
        // Syntax: condition ? valueIfTrue : valueIfFalse
        String status = (age >= 18) ? "Adult" : "Minor";
        System.out.println(status);  // Adult
        
        // Equivalent if-else
        String status2;
        if (age >= 18) {
            status2 = "Adult";
        } else {
            status2 = "Minor";
        }
        
        // Nested ternary (use sparingly)
        int score = 85;
        String grade = (score >= 90) ? "A" :
                       (score >= 80) ? "B" :
                       (score >= 70) ? "C" :
                       (score >= 60) ? "D" : "F";
        System.out.println(grade);  // B
    }
}

Ternary Best Practices

// GOOD: Simple, readable
int max = (a > b) ? a : b;

// GOOD: Default value
String name = (input != null) ? input : "Unknown";

// BAD: Nested ternary (hard to read)
// int result = x > 0 ? y > 0 ? 1 : -1 : y > 0 ? -1 : 1;

// BETTER: Use if-else for complex logic
int result;
if (x > 0) {
    result = (y > 0) ? 1 : -1;
} else {
    result = (y > 0) ? -1 : 1;
}

Operator Precedence

Operator Precedence (Highest to Lowest)

1. Postfix:      x++ x-- () [] .
2. Unary:        ++x --x +x -x ~ !
3. Multiplicative: * / %
4. Additive:     + -
5. Shift:        << >> >>>
6. Relational:   < > <= >= instanceof
7. Equality:     == !=
8. Bitwise AND:  &
9. Bitwise XOR:  ^
10. Bitwise OR:  |
11. Logical AND: &&
12. Logical OR:  ||
13. Ternary:     ? :
14. Assignment:  = += -= *= /= %= &= ^= |= <<= >>= >>>=

Common Precedence Mistakes

public class Precedence {
    public static void main(String[] args) {
        // Mistake 1: + before <<
        int a = 1 << 2 + 3;  // 1 << (2 + 3) = 32, NOT (1 << 2) + 3 = 7
        
        // Mistake 2: == before &&
        boolean b = true || false && false;  // true || (false && false) = true
        
        // Mistake 3: Unary before binary
        int x = 5;
        int y = -x + 3;  // (-5) + 3 = -2, NOT -(5 + 3) = -8
        
        // Use parentheses for clarity!
        int clear1 = (1 << 2) + 3;  // 7
        boolean clear2 = (true || false) && false;  // false
        int clear3 = -(x + 3);  // -8
        
        System.out.println("a = " + a);  // 32
        System.out.println("b = " + b);  // true
        System.out.println("y = " + y);  // -2
    }
}

Parentheses Best Practice

// ALWAYS use parentheses when unsure
int result = (a + b) * (c - d);  // clear intent

// Complex expressions
boolean valid = (age >= 18) && (hasID || isVIP);  // clear

// Bitwise operations
int flags = (1 << 3) | (1 << 5);  // clear

Practice Problems

0/3solved
Predict Output: Operator Precedence
Operator Precedence

What is the output of this code?

Example:

Input: public class Test { public static void main(String[] args) { int x = 5; int y = 10; int z = x + y * 2; System.out.println(z); } }

Output: 25

Multiplication has higher precedence: y * 2 = 20, then x + 20 = 25.

Optimal Solution — O(1) time, O(1) space

Apply operator precedence rules

public class Test {
    public static void main(String[] args) {
        int x = 5;
        int y = 10;
        int z = x + y * 2;  // * before +
        System.out.println(z);  // 5 + 20 = 25
    }
}

Edge Cases:

  • Parentheses override precedence
  • Unary operators
Predict Output: Short-Circuit
Short-Circuit Evaluation

What is the output of this code?

Example:

Input: public class Test { public static void main(String[] args) { int x = 0; boolean result = (x != 0) && (10 / x > 2); System.out.println(result); } }

Output: false

Short-circuit AND: (x != 0) is false, so second operand is never evaluated.

Optimal Solution — O(1) time, O(1) space

Understand short-circuit evaluation

public class Test {
    public static void main(String[] args) {
        int x = 0;
        boolean result = (x != 0) && (10 / x > 2);
        // (x != 0) is false, short-circuit skips second operand
        System.out.println(result);  // false
    }
}

Edge Cases:

  • Division by zero avoided
  • Non-short-circuit operators
Find Bug: Bitwise vs Logical
Bitwise Operators

Find and fix the bug in this code.

Example:

Input: public class Bug { public static void main(String[] args) { int x = 5; boolean result = x & 2 == 2; System.out.println(result); } }

Output: false (expected true)

2 == 2 is evaluated first (precedence), giving true. Then 5 & true causes compilation error. Should be (x & 2) == 2.

Optimal Solution — O(1) time, O(1) space

Use parentheses for clarity

public class Bug {
    public static void main(String[] args) {
        int x = 5;
        boolean result = (x & 2) == 2;  // parentheses!
        System.out.println(result);  // true
    }
}

Edge Cases:

  • Operator precedence with bitwise
  • Type compatibility

Quiz

1. What is the result of 7 / 2 in Java?

Question 1 options

2. What does && do in Java?

Question 2 options

3. What is 1 << 3?

Question 3 options

4. Which operator has highest precedence?

Question 4 options

Flashcards

Question

What is short-circuit evaluation?

Answer

In && and ||, if the first operand determines the result, the second operand is not evaluated. Prevents errors like division by zero.

Question

How do you check if a number is even using bitwise?

Answer

(num & 1) == 0. The last bit of even numbers is always 0.

Question

What is the difference between & and &&?

Answer

& is bitwise AND (evaluates both operands). && is logical AND with short-circuit (skips second if first is false).

Question

What does ~ (bitwise NOT) do?

Answer

Flips all bits. ~5 = -6, ~0 = -1. Uses two's complement representation.

Question

What is Operators?

Answer

Operators is a key concept in Java programming.

Revision Notes

Key Takeaways

  • 1.Integer division truncates: 7 / 2 = 3
  • 2.&& and || use short-circuit evaluation
  • 3.Use parentheses to clarify precedence
  • 4.Bitwise operators are useful for interviews (power of 2, swap, etc.)
  • 5.Always use .equals() for object comparison

Interview Tips

  • Know operator precedence for tricky expressions
  • Use short-circuit to prevent errors
  • Master bitwise tricks for optimization
  • Explain ternary vs if-else tradeoffs

Cheat Sheet

Operators Cheat Sheet

Arithmetic: +, -, *, /, %, ++, --

  • / truncates with integers
  • % gives remainder

Relational: ==, !=, <, >, <=, >=

  • Use .equals() for objects

Logical: &&, ||, !

  • Short-circuit evaluation
  • && skips second if false

Bitwise: &, |, ^, ~, <<, >>, >>>

  • (num & 1) == 0 checks even
  • num << n multiplies by 2^n
  • num >> n divides by 2^n

Ternary: condition ? val1 : val2

Precedence: * / % before + - before == != before && before ||