🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### [`System.out.format()`](https://lingcoder.gitee.io/onjava8/#/book/18-Strings?id=systemoutformat) Java SE5 引入了`format()`方法,可用于`PrintStream`或者`PrintWriter`对象(你可以在[附录:流式 I/O](https://lingcoder.gitee.io/onjava8/#/./Appendix-IO-Streams)了解更多内容),其中也包括`System.out`对象。`format()`方法模仿了 C 语言的`printf()`。如果你比较怀旧的话,也可以使用`printf()`。以下是一个简单的示例: ~~~ // strings/SimpleFormat.java public class SimpleFormat { public static void main(String[] args) { int x = 5; double y = 5.332542; // The old way: System.out.println("Row 1: [" + x + " " + y + "]"); // The new way: System.out.format("Row 1: [%d %f]%n", x, y); // or System.out.printf("Row 1: [%d %f]%n", x, y); } } /* Output: Row 1: [5 5.332542] Row 1: [5 5.332542] Row 1: [5 5.332542] */ ~~~ 可以看到,`format()`和`printf()`是等价的,它们只需要一个简单的格式化字符串,加上一串参数即可,每个参数对应一个格式修饰符。 `String`类也有一个`static format()`方法,可以格式化字符串。