Skip to content

VOL 01 / CH 03 / LESSON 01

3.1 Expressions, Assignment, and Evaluation Order ​

Prerequisites: Chapter 2; Variables, Types, and Type Conversion Estimated time: 25 minutes Practice environment: JDK 17+ and Bash; first example written to a temporary directory You are ready to continue when: You can distinguish between expressions and statements, and to use parentheses to clearly express evaluation intent

Expressions, Values, and Statements ​

java
public class Checkout {
    public static void main(String[] args) {
        int apples = 5;
        double price = 3.5;
        double total = apples * price;
        System.out.println(total);
    }
}

Create the temporary directory first. After mkdir out, save the code above as Checkout.java in the current directory, then compile and run it:

bash
chapter3_workdir=$(mktemp -d)
readonly chapter3_workdir
cd "$chapter3_workdir"
mkdir out
javac -d out Checkout.java
java -cp out Checkout

The output is 17.5.

The expressions below have types and produce values when they complete normally. Other expressions, such as a call to the void method println(...), produce no value. Evaluation can also end abruptly with an exception. Start with these value-producing examples:

CodeType or Purpose
5int literal expression
applesVariable access expression, of type int
apples * priceNumeric expression, promoted to type double
apples > 3Relational expression, of type boolean
total = apples * priceAssignment expression, with type and value derived from the variable on the left after assignment

double total = ...; is a local variable declaration statement, not an expression. total = ...; is an assignment expression used as an expression statement, its computed result is discarded. Java's "assignment itself is an expression" explains why chained assignments can be compiled:

java
int left;
int right;
left = right = 10;

Chained syntax isn't suitable for all scenarios; when types differ or the intent is unclear, separate lines are preferable.

Operand Evaluation Proceeds Left to Right ​

Java specifies a clear order for operand evaluation. Consider the following:

java
public class EvaluationOrder {
    static int mark(String label, int value) {
        System.out.println(label);
        return value;
    }

    public static void main(String[] args) {
        int result = mark("left", 2) + mark("right", 3);
        System.out.println(result);
    }
}

The output order is left, right, and the result is 5. Precedence determines how the expression is grouped and does not cause the right operand to be evaluated before the left operand.

Even in complex expressions involving assignments, ++, or method side effects, readability remains challenging. Language rules can tell you what the result will be, but they cannot make a confusing structure any clearer. Break side effects into standalone statements.

Precedence, Associativity, and Parentheses ​

java
int result = 10 + 3 * 2; // 16

Multiplication has higher precedence, so grouping is equivalent to 10 + (3 * 2).

java
int difference = 20 - 5 - 3; // 12

Subtraction has the same precedence and is left-associative, so it is equivalent to (20 - 5) - 3. Assignment typically has right-associativity, which makes left = right = 10 equivalent to left = (right = 10).

Parentheses should express business grouping, rather than enclose all symbols mechanically alone:

java
boolean eligible = isMember && (spent >= minimumSpend);
double finalPrice = eligible ? total * discountRate : total;

Do not rely on an incomplete mnemonic for operator precedence when writing production code. When three or more operators are involved, or when readers must pause to understand the expression, use named intermediate variables and parentheses to break down the expression.

String Concatenation Is Also + ​

If any operand involved in a concatenation operation is a string, + will convert the value to a string and join them together. It still follows left-associative grouping:

java
System.out.println("total=" + 1 + 2);   // total=12
System.out.println("total=" + (1 + 2)); // total=3

Heavy concatenation in logs or loops can create additional objects, this topic will be explored further in lessons on parameterized logging and StringBuilder. For now, focus on getting the parentheses correct.

Compound Assignment Goes Beyond a Shortcut ​

java
int count = 10;
count += 3;

For simple variables, it looks like count = count + 3. But compound assignment also includes implicit conversions, and the left-hand side is evaluated only once:

java
byte level = 127;
level += 1;
System.out.println(level); // -128

level = level + 1 cannot be compiled directly because level + 1 is int. level += 1 will implicitly convert the result back to byte, which may result in silent narrowing.

For array elements, fields, or left-hand expressions with side effects, the number of times each expression is evaluated can differ between the two forms. Do not simply replace compound assignment with arbitrary expansions beyond "read once, compute once, write once."

Conditional Operator ?: ​

java
String result = score >= 60 ? "pass" : "retry";

Evaluates the condition and computes only one of the two branches. It's suitable for selecting a short value, but not well-suited for embedding in complex business workflows:

java
String label = value == null
        ? "missing"
        : value.isBlank() ? "blank" : "present"; // Compiles but has high readability cost

Refactor into named methods or use if for better clarity. The types of the two branches also influence the overall type of the conditional expression. When dealing with null, boxing, or different numeric types, don't rely on intuition, hand it off to the compiler and write tests to verify behavior.

Professional Quick Reference ​

QuestionAnswer
Does every expression produce a value?No; void calls produce no value, and evaluation can end abruptly with an exception.
Is assignment an expression?Yes; the entire variable declaration is not an expression.
What is the order of operands?Java typically evaluates operands from left to right according to syntax rules.
What does precedence determine?Grouping in syntax; it does not mean operands can be rearranged arbitrarily.
Are compound assignments equivalent to simple assignments?No; they differ in implicit conversions and the fact that the left-hand side is evaluated only once.
When is a ternary operator appropriate?For short, side-effect-free conditional expressions with two possible outcomes.

Before Proceeding ​

Confirm you can distinguish between declaration statements and assignment expressions, understand operator precedence and evaluation order, and predict the left-associative result of string concatenation. Then clean up the first example:

bash
cd
ls -ld -- "$chapter3_workdir"
rm -r -- "$chapter3_workdir"

→ Next: Arithmetic, Division, and Remainders

Standard references: JLS §15.7: Expression Evaluation Order, §15.26: Assignment Operators.

Built with VitePress | Software Systems Atlas