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 trial

Java

Difference between printf and println

So, I was working on the swapHead() method in the Java track and one of the things we do which is common is that we use the ("%s", someVariable) to substitute having to hard code the names we want. That much is understandable.

But what I don't get. is why does it throw a huge error about unsuitable method and different number of arguments if you use System.out.println in stead of System.out.printf?

I was racking my brain trying to figure out why my code wasn't working. I knew everything was correct and I didn't think to change something I knew to be right until the very last ditch effort to keep my brain intact.

Can someone explain this to me? Like I am 5 even?

2 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hey Darin,

I think of the two as being "Print a Line" and "Print Formatting".

println() will print a new line and then the string inside. This method can use concatenation, but cannot understand any kind of formatting syntax inside its paretheses.

Now, if you need to do any kind of formatting on the String (eg. new lines, left align, or the type of substitution as you have above), you need to use printf(), as this uses the Formatter class and its formatting syntax.

You can pretty much do anything with printf() that can be done with println() ... but not vice versa.

If you're still not quite sure, there are many resources that describe the differences many different ways. Just Google "Java println vs printf" and you should find one that gives you that "ah-ha!" moment. :smiley:

Hope that helps. :) :dizzy:

Thanks so much for the reply. I believe that this was my "Ah-ha!" moment. I appreciate the well wishes and good tone. Forums are sometimes strange. You can get some nasty people screaming to just google things. But why have a help forum if you just want to tell people to look other place? Googling might have brought me to said forum. So once again, I appreciate the help.

printf means to state something, println means to respond to something. hope it helps!