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

Jun Dong
Jun Dong
4,754 Points

System.out.printf("The dispenser is %s %n", dispenser.characterName); What does this mean

System.out.printf("The dispenser is %s %n", dispenser.characterName); Can someone please explain what the %s and %n does?

3 Answers

%s fills in the string value from the variable, which in this case is characterName %n takes the following text to the next line

Jun Dong
Jun Dong
4,754 Points

Yeah but can't you also use \n? What's the difference between %n and \n?

Rich Zimmerman
Rich Zimmerman
24,063 Points

The printf method will print out a formatted string. The %s and %n are formatting items where %s will be formatted with the string passed as a parameter after the string (in this case, it’s dispenser.characterName). %n just adds a new line at the end of the string because printf does not add a new line by default the way println does.

I am not clear enough. Can you explain me with an example if you don't mind? Thank you

Teacher Russell
Teacher Russell
16,873 Points

You got two good answers already, but I just wanted to add, as so often is the case, it'll be extremely helpful to study the course and workshops preceding this one. Java Basics, Getting Loopy, and The Thing about Strings. I encountered the %n (that one got me, too) in the workshop, and googled it. These course are all built on top of one another, so it really pays to start at the beginning to at least scan and see what we don't know. The thing about strings is a very good video with a lot of useful info in a very short amount of time:)