Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a Java string in another string without concatenation? [duplicate]

Tags:

java

string

Is there a more elegant way of doing this in Java?

String value1 = "Testing";  
String test = "text goes here " + value1 + " more text";

Is it possible to put the variable directly in the string and have its value evaluated?

like image 483
me_here Avatar asked Apr 21 '09 14:04

me_here


2 Answers

   String test = String.format("test goes here %s more text", "Testing"); 

is the closest thing that you could write in Java

like image 165
dfa Avatar answered Sep 17 '22 09:09

dfa


A more elegant way might be:

 String value = "Testing"; 
 String template = "text goes here %s more text";
 String result = String.format(template, value);

Or alternatively using MessageFormat:

 String template = "text goes here {0} more text";
 String result = MessageFormat.format(template, value);

Note, if you're doing this for logging, then you can avoid the cost of performing this when the log line would be below the threshold. For example with SLFJ:

The following two lines will yield the exact same output. However, the second form will outperform the first form by a factor of at least 30, in case of a disabled logging statement.

logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);
like image 24
toolkit Avatar answered Sep 20 '22 09:09

toolkit