初學者常對 System.out.println("a=" + a) 中的雙引號、加號、變量拼接感到困惑:為什麼有時加號在變量前,有時在後?雙引號到底起什麼作用?

"" 表示字符串字面量凡是雙引號包裹的內容,編譯器都視為 String 類型常量,例如 "a="、"hello"。
+ 的雙重含義| 場景 | 行為 | 示例 |
|---|---|---|
| 兩側均為數值 | 數學加法 | 1 + 2 → 3 |
| 任意一側為字符串 | 字符串拼接 | "a=" + 1 → "a=1" |
int b = 1, c = 2;
System.out.println("b+c=" + b + c); // 輸出 "b+c=12" —— 從左到右依次拼接
System.out.println("b+c=" + (b + c)); // 輸出 "b+c=3" —— 括號優先執行數學加法
package Test0831;
public class QTest_3 {
public static void main(String[] args) {
int a = 10;
int b = 1, c = 2;
String str = "helloWorld!";
// 1. 字符串 + 基本類型 → 字符串
System.out.println("a=" + a); // a=10
System.out.printf("a=%d%n", a); // a=10 (格式化輸出)
// 2. 字符串 + 字符串
System.out.println("str=" + str); // str=helloWorld!
System.out.printf("str=%s%n", str); // str=helloWorld!
// 3. 關鍵對比:括號決定運算優先級
System.out.println("b+c=" + (b + c)); // b+c=3 ✅ 正確
System.out.println("b+c=" + b + c); // b+c=12 ❌ 陷阱
System.out.printf("b+c=%d%n", (b + c)); // b+c=3
}
}
"sum=" + (a + b)printf / String.format,可讀性更強log.info("a={}, b={}", a, b),避免無效拼接開銷Java 中 + 與雙引號的配合本質是「字符串拼接運算符重載」。掌握「左右操作數類型決定行為」與「括號改變優先級」兩大規則,即可輕鬆驾馭各種輸出場景。