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 Java Objects Meet Objects Creating Classes

Julian Sanchez
PLUS
Julian Sanchez
Courses Plus Student 2,108 Points

What's the difference between System.out.printnl & System.out.printf?

As far as I can see Craig uses both System.out.printnl and System.out.printf for doing the same thing which is making the console display certain text. Why is he using two different methods for doing the same thing? What is the difference between these methods?

1 Answer

println(); prints a string as a single line of text (automatically adds a newline at the end so you don't have to).

Printf just prints a formatted string using format characters. You don't use format characters with println.

printf("Hello s%!\n", firstName); 

and

println("Hello " + firstName + "!"); 

are functionally equivalent.

If you just want to print a single line of text with no formatting, it's more economical to use println() because it takes care of the newline character for you. If you want a heavily formatted string, printf() is better, but both essentially accomplish the same task in different ways.

Great