Expressions and Output
| English | Chinese | Pinyin |
|---|---|---|
| expression | 表达式 | biǎo dá shì |
| operators | 运算符 | yùn suàn fú |
| modulus | 取模 | qǔ mó |
| concatenates | 拼接 | pīn jiē |
Arithmetic expressions
- An expression 表达式 is a piece of code that computes a value.
- Java's arithmetic operators 运算符:
+,-,*,/, and%(remainder). %is the modulus 取模 operator:17 % 5is2(the leftover after dividing).- Expressions follow the usual order of operations (
*,/,%before+,-).
Precedence and grouping
- Multiplication and division bind tighter than addition and subtraction.
- Use parentheses to force the order you want:
(a + b) * c. - Operators of equal precedence evaluate left to right.
- When in doubt, add parentheses — clarity beats cleverness.
Printing output
System.out.println(x)printsxand moves to a new line.System.out.print(x)printsxwith no new line after.- The
+operator concatenates 拼接 strings:"Score: " + score. - Mixing a String with a number in
+turns the number into text.
String concatenation vs. addition
- If either side of
+is a String,+means concatenation, not addition. "" + 3 + 4gives"34"(text), but3 + 4 + ""gives"7"(added first).- Evaluation is left to right, so the first
+decides the mode. - Wrap numeric math in parentheses when concatenating:
"Sum: " + (3 + 4).
+ is overloaded: it adds numbers but concatenates Strings, left to right. "Total: " + 3 + 4 prints Total: 34 (each + hits a String), while "Total: " + (3 + 4) prints Total: 7. And % gives the remainder — great for "is it even?" (n % 2 == 0) — don't confuse it with division.
Evaluate 10 + 2 * 3:
*first:2 * 3is6.- Then
+:10 + 6is16. System.out.println("Answer: " + 16)printsAnswer: 16.
An expression computes a value using operators + - * / % under standard precedence (* / % before + -, left to right, parentheses override). % gives the remainder. Print with System.out.println (newline) or print (none); + concatenates when a String is involved — parenthesize numeric math.
Evaluating an expression step by step
- binds tighter than +, so 2*3 happens first.
Evaluate the Java expression 10 + 2 * 3.
- first (2*3=6), then + (10+6=16).
What is 17 % 5 in Java (the remainder)?
17 = 3×5 + 2, so the remainder is 2.
What does System.out.println("Total: " + 3 + 4) print?
Left to right, each + hits a String → concatenation → 34.
The operator that gives the remainder of a division is ___ (one symbol).
% is the modulus (remainder) operator.
System.out.print(x) moves to a new line after printing.
print stays on the same line; println adds the newline.