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

%d instead of %s?

Whats the difference in Java between these two? ("My name is %s", name), ("My name is %d", name). Also what's the difference in \n or %n in creating a newline in code. If there is none why do we have both.

3 Answers

Hi

re: So %n and \n are the same? and if so why have two different ways?

it really a matter of usage.

printf (f stands for formatted) needs the formatting information, and the %s, %d, %n .... provide this information. It great for readability

if you put /n in the string, then you probably get away with println. You will get the the line break, but you will loose the readability that comes with printf

there is no right/wrong here ... just use as needed.

hope this helps

%s is to prnt a string

%d is generally used to print a number

%n is for new line

Here is an example.

    System.out.printf("Hello there, I am %s and I am %d yrs old %n", "Jimmy", 99);

if this answers your question, please mark the question as answered.

So %n and \n are the same? and if so why have two different ways?

Ranvir Sahota
Ranvir Sahota
9,844 Points

Milka Vuorio I thought the same thing and this I believe is the best explanation on the internet: http://stackoverflow.com/questions/1883345/whats-up-with-javas-n-in-printf I know this is an old post but I thought I'd post it to help people out. Also %d is used to print decimal numbers I know it can be used to print integers but why use it when this %i has been made to specifcally print integers?