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?
The System. out. printf() function in Java allows users to print formatted data.
System. out. printf() method can be used to print formatted output in java.
The printf() method of Java PrintStream class is a convenience method which is used to write a String which is formatted to this output Stream. It uses the specified format string and arguments to write the string.
One, the printf (short for "print formatted") function, writes output to the computer monitor. The other, fprintf, writes output to a computer file. They work in almost exactly the same way, so learning how printf works will give you (almost) all the information you need to use fprintf.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With