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

What do we use % symbol for and why there is a comma after the string end, following a name of a variable?

and why the below code does not work?

String.firstName = "Bobby"; console.printf("Hi, my name is %s \n", firstName);

1 Answer

Hi, the % is a special character in the printf-method. The character says to insert a variable here. So it's like a placeholder. The character following % tells the printf method what type of variable is being inserted there. In your example it says %s, so the method knows it's a String that is going to be inserted.

Here you see the difference between the printf-method and the println-method (I use the System.out instead of console):

String name = "Boba Fett";

System.out.printf("The fictional character %s is a bounty hunter from the Star Wars universe.\n", name);

System.out.println("The fictional character " + name + " is a bounty hunter from the Star Wars universe.");

They do the same, but in a slightly different manner.

Now, why does your code not work? It's because of this: String*.*firstName = "Bobby";
There should not be a dot there, only a space. When you have a dot you are usually trying to access a method (or a field) on that class or that object. But here you are simply declaring and initialising a String variable by the name of firstName.

If you have any more questions, just ask.
Good luck!