Skip to content

Metadata Card

  • Prerequisites: Ch2 (Variables & Types)
  • Estimated time: 40 min
  • Core difficulty:
  • Reading mode: Easy stroll
  • Completion marker: Can write arithmetic, comparison, and logical expressions; understand operator precedence and type promotion

The Breakthrough · Tracing the Origins

You have variables — labeled storage. Now you need to do things with them. Calculate totals, compare values, make decisions. This is where expressions and operators enter.

An expression is a combination of variables, literals, and operators that evaluates to a single value.

Arithmetic Operators

java
int a = 10;
int b = 3;
int sum = a + b;      // 13
int diff = a - b;     // 7
int product = a * b;  // 30
int quotient = a / b; // 3  (integer division — truncates!)
int remainder = a % b;// 1

Language: Java Expected output: 13 7 30 3 1Try it: Change a and b to double — what changes?

Key trap: Integer division truncates! 10 / 3 is 3, not 3.333. If you want decimal division, at least one operand must be a floating-point type: 10 / 3.03.333...

Comparison Operators

java
int x = 5;
int y = 10;
boolean isEqual = x == y;    // false
boolean isNotEqual = x != y; // true
boolean isLess = x < y;      // true
boolean isGreater = x > y;   // false

Critical distinction: == compares values for primitives, but references for objects. For String comparison, use .equals().

Logical Operators

java
boolean a = true;
boolean b = false;
boolean and = a && b;  // false
boolean or = a || b;   // true
boolean not = !a;      // false

// Short-circuit evaluation:
// In `a && b`, if `a` is false, `b` is never evaluated
// In `a || b`, if `a` is true, `b` is never evaluated

Operator Precedence

Remember PEMDAS from math? Java is similar but with more operators:

  1. Postfix: expr++ expr--
  2. Unary: ++expr --expr +expr -expr !
  3. Multiplicative: * / %
  4. Additive: + -
  5. Relational: < > <= >=
  6. Equality: == !=
  7. Logical AND: &&
  8. Logical OR: ||
  9. Assignment: = += -=

When in doubt: use parentheses. They cost nothing and make your intent crystal clear.

Type Promotion

java
int a = 5;
double b = 2.5;
double result = a + b; // a is promoted to double → 7.5

// Explicit casting (narrowing):
double pi = 3.14159;
int truncated = (int) pi; // 3 — fractional part lost!

Final Challenge

  1. Write an expression that calculates the area of a circle given its radius
  2. Calculate 10 / 3 with integers, then with at least one double — observe the difference
  3. Use % to check if a number is even or odd
  4. Write a logical expression that returns true if a number is between 10 and 20 (inclusive)

Traveler's Notes

Expressions produce values. Operators manipulate values.
Integer division truncates — watch out!
&& and || short-circuit — use this intentionally.
Parentheses make precedence explicit — use them.
Type promotion happens automatically; casting is explicit narrowing.

Built with VitePress | Software Systems Atlas