Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.out.printf() usage

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?

like image 392
NoOne Avatar asked Jul 01 '18 11:07

NoOne


People also ask

What is system out printf used for?

The System. out. printf() function in Java allows users to print formatted data.

What is the use of system out format in Java?

System. out. printf() method can be used to print formatted output in java.

Can we use printf 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.

What is formatted output using printf () statement explain it?

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 Answers

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.

like image 73
xingbin Avatar answered Oct 17 '22 02:10

xingbin