user1414745
user1414745

Reputation: 1317

MessageFormat vs StringBuffer

I see, that in Java you can build strings with

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

Answers (4)

Vaibhav Jain
Vaibhav Jain

Reputation: 119

As suggested in various comment StringBuilder is fastest implementation for string concatenation. MessageFormat internally uses StringBuilder with regex overheads.

Upvotes: 1

Peter Lawrey
Peter Lawrey

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

QuokMoon
QuokMoon

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

duffymo
duffymo

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

Related Questions