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

Text Formatting

I have been rewatching the videos on Java Objects and the methods 'episode' was playing and I noticed how the Instructor would add a line and then indent after main body of the method.

I know it's bad practice too put code snippets like this but this is what I am talking about.

System.out.printf("The dispenser is %s %n", dispenser.getCharacterName() );

Is this a formatting convention that is used throughout Java or is it just for making things look pretty on the smaller viewing window for the video, as opposed to having everything on one line?

When you use printf you are formatting a string of text. The %s is basically a placeholder for what follows after the comma and the %n is a new line symbol, however, I usually use the backslash followed by the 'n': \n.
When you use printf it does not automatically bring the cursor down after the line during print out; that's why he has the new line character in there.

2 Answers

System.out.printf("The dispenser is %s %n", dispenser.getCharacterName() );

printf is for printing formatted text. In your above example, when the line is printed, the %s (a string variable) will be replaced with the value of dispenser.getCharacterName(), and %n is a newline representation.

You can read more here about printf and formatting rules. Or, if you prefer to read it directly from Java, you can read more here. Either way, I highly recommend getting comfortable with it as it's an extremely useful tool!

%s = string,
%d = decimal,
. . .
. . .

%n is kind-of special:

There is also one specifier that doesn't correspond to an argument. It is "%n" which outputs a line break. A "\n" can also be used in some cases, but since "%n" always outputs the correct platform-specific line separator, it is portable across platforms whereas "\n" is not.

Thanks for the read guys, but my post didn't turn out the way it was supposed to. I know what it does, I just had a question about the formatting of it. I hope that that my updated snippet works properly.

I hope I fixed it.

System.out.printf("The dispenser is %s %n", 
                 dispenser.getCharacterName() 
                 );