简体   繁体   English

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

[英]Difference between System.out.printf and String.format

May I know what is the difference between the two in java?我可以知道java中两者有什么区别吗? I am reading a book and it uses both methods to display strings.我正在读一本书,它使用这两种方法来显示字符串。

The first one writes to the stdout and the second one returns a String object. 第一个写入标准输出第二个返回一个String对象。

Which to use depends on the sole purpose.使用哪个取决于唯一的目的。 If you want to display the string in the stdout (console), then use the first.如果要在标准输出(控制台)中显示字符串,请使用第一个。 If you want to get a handle to the formatted string to use further in the code, then use the second.如果您想获得格式化字符串的句柄以在代码中进一步使用,请使用第二个。

String.format returns a new String, while System.out.printf just displays the newly formatted String to System.out, sometimes known as the console. String.format返回一个新的 String,而System.out.printf只是将新格式化的 String 显示给 System.out,有时也称为控制台。

These two snippets of code are functionally equivalent:这两个代码片段在功能上是等效的:

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

and

System.out.printf("%d is my favorite number", 42);

String.format formats strings, doesn't display them. String.format格式化字符串,不显示它们。 I think you mean System.out.println(String.format("......", ....)) or some similar construct ?我想你的意思是System.out.println(String.format("......", ....))或一些类似的构造?

String.format returns a formatted string. String.format返回一个格式化的字符串。 System.out.printf also prints the formatted string. System.out.printf还打印格式化的字符串。

These two methods exhibit the exact same behavior.这两种方法表现出完全相同的行为。 We can use the format(...) with String, Java.util.Formatter (J2SE 5) and also with PrintWriter.我们可以将 format(...) 与 String、Java.util.Formatter (J2SE 5) 以及 PrintWriter 一起使用。

The key different between System.out.printf() and String.format() methods is that System.out.printf()String.format()方法之间的主要区别在于

  • printf() prints the formatted String into console much like System.out.println() but printf()将格式化的字符串打印到控制台中,很像 System.out.println() 但是
  • format() method return a formatted String, which you can store or use the way you want. format()方法返回一个格式化的字符串,您可以按照自己的方式存储或使用该字符串。

Otherwise nature of use is different according to their functionalities -否则使用性质根据其功能而不同 -

A sample example to add leading zeros into a numbers :将前导零添加到数字中的示例示例:

int num = 5;      
String str = String.format("%03d", num);  // 0005    
System.out.printf("Original number %d, leading with zero : %s", num, str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM