Reputation: 1317
I see, that in Java you can build strings with
MessageFormat
and a string like "You said {0} just now"
StringBuffer
and a construct like
StringBuffer mail = new StringBuffer("Dear ");
mail.append(user.name);
mail.append(",\nCongratulations!");
....
there may be other good options, string concatenation is not one of them
So, which method should I use? My thoughts are: I have 5-6 standard texts where I have to replace some of the contents dynamically. I think it will be better to have the texts as constants somewhere (class with constants or properties file) and just make the quick replacement when I need it. Otherwise I will have strings in the middle of my source code that may be changed one day, like StringBuffer("Dear ")
.
Do I have an even better option?
Upvotes: 1
Views: 1134
Reputation: 119
As suggested in various comment StringBuilder
is fastest implementation for string concatenation. MessageFormat
internally uses StringBuilder
with regex overheads.
Upvotes: 1
Reputation: 533580
You should what you believe is the simplest and clearest. Personally I would use
String mail = "Dear " + user.name + ",\nCongratulations!";
It's shorter and more efficient than using StringBuffer or MessageFormat.
Upvotes: 1
Reputation: 4425
String str = new StringBuffer().append("Hello").append("World").toString();
System.out.println(str);
//print Hello World
it contain into package import java.text.MessageFormat;
"When you using Message format"
Object[] values = { "123456", "asdfjk" };
String output = MessageFormat.format("Value 1 equals: {0} and Value 2 equals{1}", values);
System.out.println(output);
// prints:
// The value of value 1 is: 123456 The value of value 2 is: asdfjk
Upvotes: 1
Reputation: 308848
If it's emails you'd like to generate, I'd recommend neither approach. I'd rather see a Velocity template for the lettter or email body that mapped values from Java objects in its context. That would be much easier to understand and maintain. The templates can be externalized from your code, so changes are easier.
Upvotes: 1