views:

129

answers:

3

I've been using python too much lately and I forget if there's a way to do this in Java:

print "I am a %s" % string

I googled, but it's hard to find simple stuff like this when you don't know exactly what this is called in each language.

+4  A: 
System.out.println( "I am a " + string );

But I prefer this:

System.out.println( String.format( "I am a %s", string ) );
tangens
The first one is actually i18n defect, as you simply concatenate values. Do not you use it. Ever. The second one is better, but if you have two string values, that is you have to use two "%s" placeholders, it becomes i18n defect as well: translators will not be able to re-order the sentence.
Paweł Dyda
@Paweł Dyda can you say something more on why the first one is a problem? Is it because the words may need to be reordered? For instance, is it still a problem if the terms would never be reordered such as ("My name is:" + name)? Actually, isn't it a problem to embed strings in your application at all--and if you didn't, then I'd think + and %s would be the same. Maybe I'm missing something else?
Bill K
@Bill K: Yes, that is because the whole sentence might need to be reordered. Unfortunately, you cannot say that the terms that would never be reordered exist. Depending on the target language it might need to be reordered. I bet, that in Arabic (Right To Left writting system) it should look something like: "your name :my name is". As for hardcoding strings, it is also bad practice, but I assumed that one is obvious. Incorrect string concatenation is not.
Paweł Dyda
+10  A: 

Two possible simple ways of doing it:

String yourStringHere = "human";
System.out.println(String.format("I am a %s", yourStringHere));

or

System.out.printf("I am a %s\n", yourStringHere);

Notice that the printf() will not print a newline, so you have to add it manually ("\n"). But (thanks to BalusC), you can also use "%n" in your format. It will be replaced by the default system newline character. (So: String.format("I am a %s%n", yourString))
Both prints I am a human\n.

In Java, it is called formatting. Take also a look at String.format().

Martijn Courteaux
You can also use `%n` to represent the platform default linebreak. That's better for crossplatformcompatibility :)
BalusC
+1: didn't knew PrintStream.printf(). Thanks for that.
tangens
@BalusC: Oh! Thanks, I didn't know. I will use `%n` in feature.
Martijn Courteaux
You're welcome.
BalusC
+2  A: 

You can use MessageFormat.format() to do this, but of instead %s you should use {0} (in this case).

System.out.print(MessageFormat.format("I am a {0}", string));

If you ever want to localize your program, this is the better way (or worse, depending on what you want to achieve), because it will use localized number formats automatically.

Paweł Dyda