Reputation: 195
I am new to Java. While learning the printf
method I came across the below question:
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?
Upvotes: 5
Views: 482
Reputation: 28269
1$
is called Explicit indexing, the successive format of %1$d
will not lead to the increment of index, so it will also use456
to format %b
, and according to the doc:
If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). Otherwise, the result is "true".
that's why you always get 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.
Upvotes: 7