I haven't had the chance to take any serious low-level programming courses in school. (I know I really should get going on learning the "behind-the-scenes" to be a better programmer.) I appreciate the conveniences of Java, including the ability to stick anything into a System.out.print
statement. However, is there any reason why you would want to use System.out.printf
instead?
Also, should I avoid print calls like this in "real applications"? It's probably better to to print messages to the client's display using some kind of UI function, right?
println is short for "print line", meaning after the argument is printed then goes to the next line. printf is short for print formatter, it gives you the ability to mark where in the String variables will go and pass in those variables with it. This saves from having to do a long String concatenation.
Printf() function is used to print the “character”, string, float, integer, octal, and hexadecimal values onto the output screen. We use printf() function with a %d format specifier to display the value of an integer variable.
The printf function of C can do a lot more than just printing the values of variables. We can also format our printing with the printf function. We will first see some of the format specifiers and special characters and then start the examples of formatted printing.
The printf
method of the PrintStream class provides string formatting similar to the printf
function in C.
The formatting for printf
uses the Formatter
class' formatting syntax.
The printf
method can be particularly useful when displaying multiple variables in one line which would be tedious using string concatenation:
int a = 10;
int b = 20;
// Tedious string concatenation.
System.out.println("a: " + a + " b: " + b);
// Output using string formatting.
System.out.printf("a: %d b: %d\n", a, b);
Also, writting Java applications doesn't necessarily mean writing GUI applications, so when writing console applications, one would use print
, println
, printf
and other functions that will output to System.out
.
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