Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEvan Hayes
4,093 PointsSystem.out.printf or System.out.println
I have done a couple of videos and notice that they use the printf method a lot but the println works the same way is it a problem that i use the println method because it looks a lot more readable to me.
for example in the video he uses System.out.printf("Hey %s the movie starts at 7", friend);
but the System.out.println("hey" + friend + "the movie starts at 7");
gives you the same results is there a reason to use one over the other?
2 Answers
Juraj Sallai
7,188 PointsHi Evan,
Method println() prints String on new line. You can concatenate multiple items with +. Method printf() prints formatted output in the way you mentioned:
System.out.printf("Hey %s the movie starts at 7", friend);
Which looks better than something like this, especially for big output Strings.
System.out.println("hey" + friend + "the movie starts at 7");
So it is good to avoid confusion when you are printing big Strings. Pretty good explanation is also here:
https://teamtreehouse.com/community/difference-between-systemoutprintf-and-systemoutprintln
Daniel Phillips
26,940 Pointsprintf
gives you a little more flexibility when you want to print something multiple times.
e.g. "Hey Craig, the movie starts at 7, Craig. See you then Craig."
With println, you would do it like this:
String friendToInviteToMovies = "Craig";
System.out.println("Hey " + friendToInviteToMovies + ", the movie starts at 7, " + friendToInviteToMovies + ". See you then " + friendToInviteToMovies + ".";
But with printf (or the new format), you can do this:
String friendToInviteToMovies = "Craig";
System.out.printf("Hey %1$s, the movie starts at 7, %1$s. See you then %1$s.%n", friendToInviteToMovies);