* This is the 26th day of my participation in the August More Text Challenge
The conceptual differences are as follows:
Print displays its arguments in the command window and positions the output cursor after the last character displayed.
Println displays its arguments in the command window and ends with a newline character that positions the output cursor at the beginning of the next line. \
Printf is a formatted output.
\
For example, the code looks like this:
package other; public class TestPrint { public static void main(String[] args) { int i = 4; double j = 5; System.out.print(” print I :”+ I); System.out.println(” println :”+ I); System.out.printf(” I = %d,j = %f”, I,j); }} \
\
Print I :4 print I :4 I :4 j: 5.000000\
As you can see, in the print output, after I not line, use println output results directly behind the print output statements, and output a newline after println, so use printf output, the output in the second line. \
So let’s focus on printf
“I value %d,j value %f” in the string “%d” becomes the value of I, and “%f” becomes the value of j! Here, “%d” means a placeholder for an int value, and “%f” is a dot symbol for a double or float value, whose arguments are provided later. Note that the argument names must be sorted in order. Otherwise it would be wrong. And the type has to match. If we change the statement to system.out.printf (” I is %d,j is %f”, j, I); // if %d is double, %d is int, %d is double, %d is int, %d is double, %d is double So there was a mistake. And “%s” is a dot character for a string value. %c” is the point character meaning of a character value. Why is the j output 5.000000? That’s because double has six decimal places by default, but if you want to print only two decimal places, ok? B: yes, you can! Just change the words! System.out.printf(” I = %d,j = %.2f”, I,j); Here “%.2f” means output two decimal points. If you want to print three digits then “%.3f”. Now, printf turns out to be useful, too. This allows you to control the format of the output. \
\
Another example could be:
public class TestPrint { public static void main(String[] args) { int i = 4; Double j = 5.000 f; System.out.printf(” I = d,n”, I); } \
}
\
The result is: the value of I is 00004. The original “D” means 5 placeholders. If the number is less than 5, the left side is filled with 0. \
Note the difference between %d and d here!!