不是“八股”,也不是“造火箭”
1 个main()就能跑通,考语法、考细节、考调试——
答对 3 问 → 基础稳;答对 5 问 → 细节怪;全部秒解 → 大佬收徒!😎
🔍 题目代码:复制即可跑
public class JavaPuzzle {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String("Hello");
String s3 = s2.intern();
System.out.println(s1 == s2); // ①
System.out.println(s1 == s3); // ②
System.out.println(s1.equals(s3)); // ③
int x = 5;
Integer y = 5;
Integer z = 5;
System.out.println(x == y); // ④
System.out.println(y == z); // ⑤
int a = 1;
int b = a++ + ++a + a--;
System.out.println(b); // ⑥
try {
System.out.println("try");
throw new RuntimeException("boom");
} catch (Exception e) {
System.out.println("catch");
return; // ⑦
} finally {
System.out.println("finally");
}
}
}
❓ 问题清单:先写答案再运行!
- ① 输出
true还是false? - ② 输出
true还是false? - ③ 输出
true还是false? - ④ 输出
true还是false?(自动拆箱) - ⑤ 输出
true还是false?(Integer 缓存) - ⑥ 变量
b最终值是多少?(自增运算符) - ⑦
finally会不会被执行?(return 与 finally 顺序)
✅ 答案 & 解析(写完再对!)
| 题 | 答案 | 一句话解析 |
|---|---|---|
| ① | false | new 创建新对象,不在常量池 |
| ② | true | intern 把 s2 拖进常量池,与 s1 同一引用 |
| ③ | true | equals 只比较内容 |
| ④ | true | 自动拆箱,int 值 5 == 5 |
| ⑤ | true | Integer 缓存 -128~127,5 在范围内 |
| ⑥ | 7 | 步骤:1 + (++a→2) + (a--→2) → 1+3+3=7 |
| ⑦ | 会 | finally 永远执行,在 return 之前 |
🏁 拓展思考(进阶)
- 把
Integer y = 128; Integer z = 128;再运行 ⑤,结果? - 把
a++ + ++a改成++a + a++,b 值变多少? - 在 finally 里再加
return 999;,main 最终返回?