Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Arrays Iteration Enhanced For Loop

System.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
Juraj Sallai
7,188 Points

Hi 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

printf 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);