Nanfeng

Notes on software development, code, and curious ideas

Expressions, Statements, and Blocks in Java

Expressions

A Java expression combines variables, literals, operators, and method calls to produce a value.

1
2
3
4
int a = 10;
int b = 20;
int c = (a + b) * 2; // Arithmetic expression
boolean larger = c > b; // Boolean expression

Arithmetic expressions

Common arithmetic operators include +, -, *, /, %, ++, and --.

1
2
int result = 10 / 3;
System.out.println(result); // 3

Integer division discards the fractional part. Use a floating-point operand when a fractional result is needed:

1
double result = 10.0 / 3;

Prefix increment changes the variable before its value is used; postfix increment supplies the old value first:

1
2
3
4
5
6
int number = 10;
System.out.println(++number); // 11

number = 10;
System.out.println(number++); // 10
System.out.println(number); // 11

Boolean expressions and short-circuiting

Boolean expressions produce true or false and often combine comparison operators with &&, ||, and !.

1
2
int age = 20;
boolean permitted = age >= 18 && age < 65;

&& 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:

1
2
3
if (name != null && !name.isEmpty()) {
System.out.println(name);
}

Statements

A statement is a complete unit of execution. Many simple statements end with a semicolon:

1
2
3
4
total = price * quantity; // Assignment statement
counter++; // Increment statement
printResult(total); // Method invocation statement
Widget widget = new Widget(); // Declaration and object creation

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:

1
2
3
4
if (score >= 60) {
String message = "Pass";
System.out.println(message);
}

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.

+