String#format
more: link (opens new window)
%d: long, int%s: String, boolean, object%f: float%.1f: Formats a floating-point number with 1 decimal places. 这里不能加 0, 如0.xxx%.2f: Formats a floating-point number with 2 decimal places
# 包装类型
# 需要判空
Integer count = null;
System.out.printf("Count: %d%n", count != null ? count : 0);
1
2
2
# 通用方式
Integer count = null;
Double ratio = 2.345;
System.out.printf("Count: %s, Ratio: %s%n", String.valueOf(count), String.valueOf(ratio));
// Output: "Count: null, Ratio: 2.345"
1
2
3
4
2
3
4
优点: 这处理方式既能避免空指针异常,还保持了输出的通用性,非常适合于不确定类型或可能为 null 的变量
上次更新: 2026/10/18, 22:14:48