if / else

if (x > 0) {
    System.out.println("正");
} else if (x == 0) {
    System.out.println("零");
} else {
    System.out.println("负");
}

单语句可省 {}(但推荐永远写——少坑):

if (x > 0) System.out.println("正");

三元

String sign = x > 0 ? "正" : x < 0 ? "负" : "零";

switch 语句(老式)

switch (day) {
    case 1:
    case 2:
        System.out.println("工作日开始");
        break;
    case 6:
    case 7:
        System.out.println("周末");
        break;
    default:
        System.out.println("中间");
}

每个 case 末尾必须 break——否则 fallthrough(穿透)。是 Java 的"老坑"。

switch 表达式(Java 14+,现代写法)

String description = switch (day) {
    case 1, 2 -> "工作日开始";
    case 6, 7 -> "周末";
    default -> "中间";
};
  • -> 替代 case ... : break
  • 多个值用逗号
  • 必须穷举(漏了某个枚举值编译错)
  • 返回值

新代码全部用箭头版——简洁、强类型、强检查。

块体 + yield

String msg = switch (n) {
    case 1 -> "one";
    case 2 -> {
        System.out.println("二");
        yield "two";          // 块体里用 yield 返回
    }
    default -> "other";
};

for(传统)

for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

for (int i = 9; i >= 0; i--) {
    System.out.println(i);
}

enhanced for(foreach)

int[] arr = {1, 2, 3};
for (int n : arr) {
    System.out.println(n);
}

List<String> list = List.of("a", "b", "c");
for (String s : list) {
    System.out.println(s);
}

Map<String, Integer> m = Map.of("a", 1, "b", 2);
for (var entry : m.entrySet()) {
    System.out.println(entry.getKey() + "=" + entry.getValue());
}

任何实现 Iterable<T> 的都能用——数组、所有集合、Files.lines(path) 等。

while / do-while

while (cond) {
    ...
}

do {
    ...
} while (cond);     // 注意结尾分号

break / continue

for (int x : items) {
    if (x.isBad()) continue;     // 跳过本次
    if (x.isEnd()) break;         // 退出循环
    process(x);
}

标签 break(跳多层)

outer:
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        if (matrix[i][j] == target) {
            break outer;     // 跳出 outer 那层
        }
    }
}

continue outer;

避免滥用——大多数情况重构成方法 + early return 更清楚。

try / catch / finally

try {
    doRisky();
} catch (FileNotFoundException e) {
    System.err.println("没找到: " + e.getMessage());
} catch (IOException e) {
    System.err.println("IO 错: " + e.getMessage());
} catch (Exception e) {
    System.err.println("其他: " + e);
} finally {
    cleanup();
}

详见 第 19 篇

try-with-resources(自动关闭)

try (var reader = Files.newBufferedReader(Path.of("data.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}   // reader 自动 close(哪怕里面抛异常)

任何实现 AutoCloseable 的资源都能放——文件、流、连接。

Java 9+ 支持已有变量:

var reader = Files.newBufferedReader(Path.of("data.txt"));
try (reader) {
    ...
}

return early

public String describe(User u) {
    if (u == null) return "null user";
    if (u.isAdmin()) return "admin";
    if (u.isGuest()) return "guest";
    return "user " + u.getName();
}

Java 习惯:早返回胜过嵌套 if-else。

yield 不止在 switch

Java 21+ 还有 Thread.yield() 让 CPU(与虚拟线程协作调度有关)——但作为关键字 yield 只在 switch 块体内。

while(true) + break

模拟 do-while-mid 模式:

while (true) {
    var line = reader.readLine();
    if (line == null) break;          // 中间退出
    process(line);
}

switch + 模式匹配(Java 21+,正式)

Object obj = ...;

String s = switch (obj) {
    case Integer i -> "int: " + i;
    case String str -> "string: " + str;
    case null -> "null";
    default -> "other";
};

详见 第 17 篇

→ 下一篇 方法