Falmarri
Falmarri

Reputation: 48559

String formatting in Java

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.

Upvotes: 3

Views: 434

Answers (3)

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

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().

Upvotes: 10

Paweł Dyda
Paweł Dyda

Reputation: 18662

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.

Upvotes: 2

tangens
tangens

Reputation: 39733

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

But I prefer this:

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

Upvotes: 4

Related Questions