简体   繁体   English

System.out.printf 与 System.out.format

[英]System.out.printf vs System.out.format

System.out.printfSystem.out.format是否完全相同,或者它们在某种程度上有所不同?

System.out is a PrintStream , and quoting the javadoc for PrintStream.printf System.out是一个PrintStream ,并引用了PrintStream.printf的 javadoc

An invocation of this method of the form out.printf(l, format, args) behaves in exactly the same way as the invocation out.format(l, format, args)out.printf(l, format, args)形式调用此方法的行为与调用out.format(l, format, args)完全相同

The actual implementation of both printf overloaded forms两种printf重载形式的实际实现

public PrintStream printf(Locale l, String format, Object ... args) {
    return format(l, format, args);
}

and

public PrintStream printf(String format, Object ... args) {
        return format(format, args);
}

uses the format method's overloaded forms使用format方法的重载形式

public PrintStream format(Locale l, String format, Object ... args)

and

public PrintStream format(String format, Object ... args)

respectively.分别。

没有区别。他们都表现得一样

The key difference between printf and format methods is: printfformat方法之间的主要区别是:

  • 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.否则,使用性质根据其功能而有所不同。 An example to add leading zeros to a number:向数字添加前导零的示例:

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

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

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