What is the difference between printf() and print()?

Asked

Viewed 1,866 times

12

I was doing some simple algorithms in Java and most of the time it is used System.out.println() or System.out.print(), but to make the definition of the number of decimal places I am using System.out.printf(). I know there is a difference between the first two, both in operation and implementation. But what is the difference between them and the last?

1 answer

14


The most common in Java is to use System.out.print() (or with the ln if you want to skip line, but this you already know) but if you need certain formatting the use of System.out.printf() may be more suitable. This method works very similar to printf() of C using the Formatter.

Example:

System.out.print("x: " + x + " y: " + y);
System.out.printf("x: %d y: %d", x, y);

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Besides being more practical in several situations can also be quite useful where has localization of texts or other forms of parameterization of these texts.

  • Very enlightening Formatter class, grateful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.