[英]System.out.printf() usage
I am new to Java. 我是Java新手。 While learning the printf
method I came across the below question: 在学习printf
方法时,我遇到了以下问题:
What would be the output of following program? 以下程序的输出是什么?
System.out.printf("%1$d + %b", 456, false);
System.out.println();
System.out.printf("%1$d + %b", 456);
The answer is: 答案是:
456 + true
456 + true
Can someone help me to understand how true is getting printed without me passing it? 有人可以帮助我理解如果没有我传递它是如何真实的?
1$
is called Explicit indexing , the successive format of %1$d
will not lead to the increment of index, so it will also use 456
to format %b
, and according to the doc : 1$
被称为显式索引 , %1$d
的连续格式不会导致索引的增量,因此它也将使用456
格式化%b
,并根据文档 :
If the argument arg is null, then the result is "false". 如果参数arg为null,则结果为“false”。 If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). 如果arg是布尔值或布尔值,则结果是String.valueOf(arg)返回的字符串。 Otherwise, the result is "true". 否则,结果为“true”。
that's why you always get true
. 这就是为什么你总是true
。
To get false: 弄错:
System.out.printf("%1$d + %b", null); // null + false
or remove explicit indexing: 或删除显式索引:
System.out.printf("%d + %b", 456, null); // 456 + false
Check the doc of java.uti.Formatter
for more. 查看java.uti.Formatter
的doc以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.