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

Sam Donald
Sam Donald
36,305 Points

String order

From Stage 1: Getting Started with Java.

I have passed the code challenge but I don't think it's right.

The vid asks' us to print the string "<YOUR NAME> can code in Java!" to the console.

However the only way I could pass was like so: String firstName = "Sam"; console.printf("%s can code in Java!", firstName);

But wouldn't this print "can code in Java! Sam", when it should be "Sam can code in Java!".

How do you put the variable firstName before the string?

2 Answers

Stone Preston
Stone Preston
42,016 Points

your code is correct

String firstName = "Sam"; 
console.printf("%s can code in Java!", firstName);

will output "Sam can code in Java!"

the way printf works is that it inserts whatever variables you pass it (firstName in this case) wherever the format specifier is (%s). so since you had %s at the beginning of hte string, the value of first name got inserted there

to print the value at the end of the string you would use:

String firstName = "Sam"; 
console.printf("can code in Java! %s", firstName);

that would output "can code in Java! Sam" since the format specifier went at the end.

the specifier can go anywhere in the string and you can have more than one:

String firstName = "Sam"; 
String lastName = "Donald";
console.printf("%s %s can code in Java!", firstName, lastName);

when you have more than one specifier, the strings are inserted in the order you provide them in. since firstName comes first, its gets inserted at the first %s, then lastName is inserted at the next one outputting "Sam Donald can code in Java!"

like I said the specifiers can go anywhere in the string:

String firstName = "Sam"; 
String lastName = "Donald";
console.printf("%s can code %s in Java!", lastName, firstName);

outputs "Donald can code Sam in Java". Notice how lastName is inserted first, since it comes first in the list of arguments