Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized Strings in Java

Tags:

java

I find myself very frequently wanting to write reusable strings with parameter placeholders in them, almost exactly like what you'd find in an SQL PreparedStatement.

Here's an example

private static final String warning = "You requested ? but were assigned ? instead.";  public void addWarning(Element E, String requested, String actual){       warning.addParam(0, requested);      warning.addParam(1, actual);      e.setText(warning);      //warning.reset() or something, I haven't sorted that out yet. } 

Does something like this exist already in Java ? Or, is there a better way to address something like this ?

What I'm really asking: is this ideal ?

like image 873
JHarnach Avatar asked Apr 04 '12 20:04

JHarnach


People also ask

What is parameterized string in Java?

Since Java 5, you can use String.format to parametrize Strings. Example: String fs; fs = String.format("The value of the float " + "variable is %f, while " + "the value of the " + "integer variable is %d, " + " and the string is %s", floatVar, intVar, stringVar);

What is parameterized string?

Cursor addressing and other strings requiring arguments are described by a argumentized string capability with escapes in a form (%x) comparable to printf(). For example, to address the cursor, the cup capability is given, using two arguments: the row and column to address to.

What is string format () used for Java?

The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.


2 Answers

String.format()

Since Java 5, you can use String.format to parametrize Strings. Example:

String fs; fs = String.format("The value of the float " +                    "variable is %f, while " +                    "the value of the " +                     "integer variable is %d, " +                    " and the string is %s",                    floatVar, intVar, stringVar); 

See http://docs.oracle.com/javase/tutorial/java/data/strings.html

Alternatively, you could just create a wrapper for the String to do something more fancy.

MessageFormat

Per the comment by Max and answer by Affe, you can localize your parameterized String with the MessageFormat class.

like image 81
Garrett Hall Avatar answered Sep 21 '22 04:09

Garrett Hall


You could use String.format. Something like:

String message = String.format("You requested %2$s but were assigned %1$s", "foo", "bar"); 

will generate

"You requested bar but were assigned foo" 
like image 23
Keith Randall Avatar answered Sep 18 '22 04:09

Keith Randall