Java Expressions, Statements and Blocks: Operators, Logic and Scope
Expressions
A Java expression combines variables, literals, operators, and method calls to produce a value.
Arithmetic expressions
Common arithmetic operators include +, -, *, /, %, ++, and --.
Integer division discards the fractional part. Use a floating-point operand when a fractional result is needed:
| |
Prefix increment changes the variable before its value is used; postfix increment supplies the old value first:
Boolean expressions and short-circuiting
Boolean expressions produce true or false and often combine comparison operators with &&, ||, and !.
&& does not evaluate its right operand when the left operand is false. || does not evaluate the right operand when the left operand is true. This short-circuit behavior can avoid unnecessary work and null dereferences:
Statements
A statement is a complete unit of execution. Many simple statements end with a semicolon:
Control-flow constructs such as if, for, while, switch, return, break, and continue organize when statements execute.
Blocks
A block groups zero or more statements inside braces:
Variables declared inside a block are local to that block. Braces also define class, method, constructor, loop, and exception-handling bodies. Consistent indentation is not part of Java syntax, but it is essential for making nested blocks understandable.