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 Data Structures Efficiency! Menu UI

Colby Wise
Colby Wise
3,165 Points

Clarification: What is the difference and when to use: "System.out.printf" vs .println vs .print?

We often switch between using the above print methods from System console. What is the logic/reasoning behind this?

2 Answers

andren
andren
28,524 Points

printf (print formatted) is for printing formatted strings, in other words for strings that contains placeholders like %s. Example:

String name = "André";
System.out.printf("My name is %s", name);
// Prints: "My name is André"

In the above example I use the %s placeholder to embed the contents of a string variable into the string, %s is not the only placeholder formatted strings support, there are quite a few others for other types of data. You can also control how that data is displayed when you embed it in a formatted string. Like only displaying a certain number of decimals of a float/double number and the like.

Placeholders like %s is only supported when using printf. The disadvantage of using printf when not actually printing a formatted string is that you cannot use the % symbol in your string without "escaping" it. Meaning that you explicitly tell printf to treat the % as a literal character, rather than the start of a placeholder symbol like it would normally do.

For example:

System.out.printf("I got 88% on my last test.");
// This will crash your program, due to the % not being escaped

In order to escape % symbols in formatted strings you place another % symbol before it like this:

System.out.printf("I got 88%% on my last test.");
// Prints: "I got 88% on my last test."

println (print line) prints strings without trying to perform any formatting on them, so you can use whatever symbols you want (with the exception of quote marks) within your string without escaping it.

println also automatically places a line break at the end of your string. So that the next thing you print will be placed on a new line.

print is like println expect that it does not place a line break at the end of the string. Meaning that if you print multiple things with print they will all appear on the same line unless you place a line break in your string manually.

Colby Wise
Colby Wise
3,165 Points

Really thorough answer. Many thanks Andren