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
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;// 1Language: Java Expected output: 13 7 30 3 1Try it: Change a and b to double — what changes?
Key trap: Integer division truncates!
10 / 3is3, not3.333. If you want decimal division, at least one operand must be a floating-point type:10 / 3.0→3.333...
Comparison Operators
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; // falseCritical distinction: == compares values for primitives, but references for objects. For String comparison, use .equals().
Logical Operators
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 evaluatedOperator Precedence
Remember PEMDAS from math? Java is similar but with more operators:
- Postfix:
expr++expr-- - Unary:
++expr--expr+expr-expr! - Multiplicative:
*/% - Additive:
+- - Relational:
<><=>= - Equality:
==!= - Logical AND:
&& - Logical OR:
|| - Assignment:
=+=-=
When in doubt: use parentheses. They cost nothing and make your intent crystal clear.
Type Promotion
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
- Write an expression that calculates the area of a circle given its radius
- Calculate
10 / 3with integers, then with at least onedouble— observe the difference - Use
%to check if a number is even or odd - 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.