我有一个类似于在 Java 中使用“printf”而不是“print”的充分理由吗?. 该问题询问并回答了使用System.out.print
over的好处System.out.printf
。我很好奇首先使用System.out.print
over的好处System.out.printf
。
根据我的经验,我看到System.out.print
使用的频率比System.out.printf
.
使用System.out.printf
,格式化数字时更具可读性。+
如第二个 System.out 所示, 您仍然拥有用 's 连接字符串的语法糖。如果你想用它做任何事情,System.out.printf
也会返回一个。PrintStream
例子:
int hour = 6;
int minutes = 5;
int seconds = 4;
System.out.printf("Time: %d:%02d:%02d", hour, minutes, seconds);
System.out.printf("Time: " + hour + ":%02d:%02d", minutes, seconds);
System.out.print("Time: " + hour + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
//Output for each line: Time: 6:05:04
System.out.printf("Print something!");
System.out.print("Print something!");
//Output for each line: "Print something!"
System.out.printf("End a line\n");
System.out.println("End a line");
//Output for each line: End a line [followed by a line break]
String x = "a variable";
System.out.printf("Add %s", x);
System.out.printf("Add " + x);
System.out.print("Add " + x);
//Output for each line: Add a variable
因此,除了(我认为)大多数 Java 程序员使用. 之外System.out.print
,它有什么好处System.out.printf
呢?内存或时间效率是否有明显差异?