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.
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.
System.out.println( "I am a " + string );
But I prefer this:
System.out.println( String.format( "I am a %s", string ) );
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()
.
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.