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 Harnessing the Power of Objects Constants

Ranak Bansal
Ranak Bansal
1,207 Points

Why did the teacher use %d and %n instead of %s and /n?

In previous lessons the teacher always used %s (now he used %d) when inserting a variable and /n (now he used %n) when creating a new line. How come he switched? Did he talk about this in a previous lesson that I missed, or what?


2 Answers

Cam Richardson
Cam Richardson
Front End Web Development Treehouse Moderator 16,895 Points

I believe he briefly explains the difference in a later lesson, but I can provide some explanation for reference.

%d is for when you're referencing a number in the formatted string specifically. Likewise %s is for String variables.

For the newline characters each OS handles them differently. *nix based systems (MacOS, Linux, etc.) expect a \n to denote a newline. Windows actually expects something different: \r\n. So when you type \n, you run the risk of having your string being incorrectly formatted on other platforms. Java has a built in solution for this in formatted strings which is %n. This automatically adds the platform appropriate newline character sequence for you so you don't have to worry about it.

Hope that helps!

Thank you <3

Thanks for the info. I found your explanation very useful! :)