Operators & Expressions

☕ Java Lesson 3 Beginner

Operators are symbols used to perform operations on variables and values. Java includes standard arithmetic, assignment, relational, and logical operators.

1 Arithmetic & Operator Precedence (PEMDAS)

Java evaluates expressions using operator precedence similar to mathematical PEMDAS rules (Parentheses, Multiplication/Division/Modulus, Addition/Subtraction). Modulus (`%`) yields the remainder of a division.

⚠️ Integer Division Caveat: Dividing two integers in Java always yields an integer. For example, `5 / 2` evaluates to `2`, not `2.5`. To get decimal precision, at least one operand must be a double/float: `5.0 / 2` evaluates to `2.5`.
2 Increment and Decrement: Prefix vs Postfix

The increment operator (`++`) increases a variable's value by 1. However, where it is placed changes execution behavior:

  • Postfix (`x++`): The current value of `x` is evaluated in the expression first, and then `x` is incremented.
  • Prefix (`++x`): `x` is incremented first, and then its new value is evaluated in the expression.
Java — Arithmetic & Increments ▶ Run Code
public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        
        System.out.println("Basic Division: " + (a / b));
        System.out.println("Integer Division Caveat (5 / 2): " + (5 / 2));
        System.out.println("Fixed Division (5.0 / 2): " + (5.0 / 2));

        // Prefix vs Postfix Tracing
        int x = 5;
        int y = x++; // y gets 5, then x becomes 6
        System.out.println("Postfix: y=" + y + ", x=" + x);

        int p = 5;
        int q = ++p; // p becomes 6, then q gets 6
        System.out.println("Prefix: q=" + q + ", p=" + p);
    }
}
3 Logical Operators & Short-Circuit Evaluation

Logical operators combine multiple conditional states:

  • And (`&&`): Evaluates to true if both conditions are true.
  • Or (`||`): Evaluates to true if at least one condition is true.
  • Not (`!`): Inverts boolean states.

Short-Circuiting: If Java evaluates the first argument of an `&&` operator as `false`, it knows the overall result will be `false` and skips evaluating the second argument entirely. Similarly, if the first argument of `||` is `true`, the second is skipped. This prevents unnecessary computation and potential runtime exceptions.

4 Code Challenge
Challenge: Write a program that initializes `int count = 10`. Print out the result of `count++` and then `++count`. Add a short-circuit expression checking if `(count > 10 || (10 / 0 == 0))` and explain why this code does not crash with an ArithmeticException.