• Post Reply Bookmark Topic Watch Topic
  • New Topic

Printf vs. Println  RSS feed

 
Paul Peterson
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have what may be a dumb question.  Is one or the other printf or println more correct?  For example:

I could display the same thing by entering

System.out.println ("Last Name:  " + lastName);

or

System.out.printf ("Last Name:  %s%n", lastName);

Is one generally more accepted than the other?  I know that printf makes formattimg much easier.  Personally, I  prefer to use printf over println.
 
Junilu Lacar
Sheriff
Posts: 11493
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not a dumb question. It's fair to wonder what other people do and it's also fair to think that what most people do is out of ignorance of any other way to do it. I personally prefer printf too because you have a lot more control over how things are displayed. println() and print() force you to do String concatenation most of the time and it's rather silly to mix println() and String.format() which gives you printf() capabilities. I even mix and match sometimes, usually because my fingers find it easier to println() than to type the equivalent printf("%n").
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
println is easier to learn, because you don't have to learn the many % tags. But I agree with Junilu that printf gives us so much more flexibility. Not only can you format your output better, but you can also squeeze more into one statement.
System.out.printf("%s %6.2f %d%n%s %12d %b %h%n%n", ...);
allows you to print several lines simultaneously. You probably get slightly faster execution because access to the terminal/command line is probably much slower than creating the formatted String to print.
The one thing you shouldn't do is this sort of thing:-
System.out.print("\n");
I prefer printf myself.
 
Paul Peterson
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your feedback!
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am actually torn. Being a Java programmer, even before Java 1.0, part of me prefer using println() over printf(). On the other hand, being a C programmer for many years before Java, another part of me prefer printf() over println()...

Henry
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you seen the March of Progress on Cay Horstmann's website?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!