Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good reason to use "printf" instead of "print" in java?

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?

like image 706
tomato Avatar asked Feb 14 '09 00:02

tomato


People also ask

Why we use printf instead of Println in Java?

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.

Why do we need printf?

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.

Can we use printf () apart from just printing values in Java?

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.


1 Answers

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.

like image 146
coobird Avatar answered Oct 14 '22 10:10

coobird