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 Basics Getting Started with Java Strings and Variables

Not understanding what exactly %s is a stand-in for.

So in Craig's Intro to Java Course he introduces a stand in for a string variable as %s....but doesn't elaborate much on this, even though it's used heavily in the following videos. I'm not sure what exactly the % is...and if the "s" is merely an arbitrary letter or if the compiler doesn't "know" what type the stand-in is without the 's' for string. In a later video he mentions something like:

console.printf("%s is a %s dude", noun, adj);

Are these stand-ins for variables always presented this way? Wouldn't it be less confusing (at least to me) to re-write it like this:

console.printf(Noun + " is a" + Adj + " dude.") ;

Why would/wouldn't you want to use the variable names themselves vs. the %s stand-in?

4 Answers

Joseph Frazer
Joseph Frazer
5,404 Points

%s is a replacement area for a string. Lets say I have this string:

String myName = "Erick";

And if we want to print that string out in a middle of a string:

console.printf("My name is %s and I love programming!", myName);

What we do is replace the %s for a string variable. Using this makes it easier to place variables in middle of sentences without having to keep using the comma. And you can use whatever way is comfortable to your needs. If you have any further questions I am here to help!

Joseph Frazer : So would we need to change the % to %i for ints? Or %f for floats? Basically, is the alphabetical letter included after the % symbol arbitrary or does it serve a specific purpose, such as delineating the type? Like why couldn't I write:

console.printf("My name is % and % is % and the answer to the universe is %.", adv, verb, participle, number);  

I'm also not sure what you mean by "without having to keep using the comma"....are you referring to breaking up the sentence to insert the name of the variable?

Joseph Frazer
Joseph Frazer
5,404 Points

Not exactly. For integers we use %d.

Joseph Frazer
Joseph Frazer
5,404 Points

By using the comma I mean by adding. You used the plus which is perfectly fine. My , is your +.