beginnerFree

Operators & Expressions

Arithmetic, comparison, logical, and ternary

Operators & Expressions

Operators combine values into expressions that produce results.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:27

The Big Picture

Operators perform calculations, comparisons, and logic. Expressions combine operators and operands to produce values.

  • Arithmetic: + - * / % for math operations
  • Comparison: == != < > <= >= return boolean
  • Logical: && || ! for combining conditions
  • Bitwise: & | ^ ~ << >> >>> for bit manipulation

How It Works

Precedence determines order: * before +, comparisons before &&. Use parentheses for clarity in complex expressions.

  • Short-circuit: && stops if left is false
  • Integer division truncates: 7 / 2 = 3
  • Use double for decimal results
  • Increment: ++i (pre) vs i++ (post) differ in timing

In the Java Landscape

Java has no operator overloading (unlike C++).

  • + only works for primitives and String concatenation
  • Bitwise operators for flags, encryption, low-level code
  • Ternary: x > 0 ? "pos" : "neg"
  • instanceof checks type (pattern matching in Java 16+)
  • Math.addExact() (Java 8) detects overflow

Pitfalls and Best Practices

  • Use equals() for objects, not == (compares references)
  • Watch division by zero - ArithmeticException for integers
  • Floating-point gives Infinity/NaN instead
  • Avoid side effects in complex expressions
  • Integer overflow wraps silently - use exact methods
  • Parentheses always clarify intent - use them liberally
#java#fundamentals#operators