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 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,894 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! :)