System.out.printf和String.format之间的区别

sut*_*toL 16 java

我可以知道java中两者有什么区别?我正在读一本书,它可以使用它来显示字符串.

Bal*_*usC 21

所述第一个写入标准输出和所述第二个返回一个String对象.

使用哪个取决于唯一的目的.如果要在stdout(控制台)中显示字符串,请使用第一个字符串.如果要获取格式化字符串的句柄以在代码中进一步使用,则使用第二个.


Gre*_*ase 8

String.format返回一个新的String,System.out.printf只显示新格式化的String到System.out,有时也称为控制台.

这两段代码在功能上是等效的:

String formattedString = String.format("%d is my favorite number", 42);
System.out.print(formattedString);
Run Code Online (Sandbox Code Playgroud)

System.out.printf("%d is my favorite number", 42);
Run Code Online (Sandbox Code Playgroud)

  • 即使这篇文章真的很老,我只想在你的答案中添加一些内容:这两个片段并不完全相同.System.out.printf不插入新行. (6认同)