0

What is the best/better approach to writing below code?

I need to send a welcome message to my user like,

Hello FirstName, thanks for choosing example.com. Your registered email is firstname.lastname@example.com

The current implementation that I have is,

public static final String WELCOME_MSG = "Hello %s, thanks for choosing example.com. Your registered email is %s"; 
System.out.println(String.format(WELCOME_MSG, firstName, email));

Now, what could be a better approach in terms of memory and computation?

One approach came to my mind is, break the constant in multiple parts like

public static final String HELLO_MSG = "Hello ";
public static final String THANKS_MSG = ", thanks for choosing example.com. Your registered email is ";
System.out.println(HELLO_MSG + firstName + THANKS_MSG + email);

But, if I think about multiple cases like this, is it good?

Thanks in Advance!

bbrinck
  • 953
  • 1
  • 9
  • 33
mehtas
  • 49
  • 1
  • 8
  • Are you planning on using it for just generating that specific sentence or are you planning on using it with variations and such? – Quadrivics Jan 03 '20 at 07:09
  • "in terms of memory and computation" - these terms are completely irrelevant, as whatever you do with the result will take way longer than the string generation. And even if not, you're not planning to generate billions of messages, are you? – maaartinus Jan 03 '20 at 08:44
  • Yes, I am planning to use it in multiple places. This one is just an example. – mehtas Jan 03 '20 at 09:27

2 Answers2

1

Try below code,

StringBuilder welcomeMsg = new StringBuilder();
welcomeMsg.append("Hello ");
welcomeMsg.append(firstName);
welcomeMsg.append(", thanks for choosing example.com. Your registered email is ");
welcomeMsg.append(email);
System.out.println(welcomeMsg.toString());
Vivek
  • 376
  • 1
  • 14
1

If you have only this requirement then this kind of String concatenations are good:

In Terms of performance concatenations have edge over format method:

Is it better practice to use String.format over string Concatenation in Java?

If you rather want very big dynamic message to be generated then you need to choose between String Concatenation and String Builder.Good latency analysis is still required:

https://kylewbanks.com/blog/java-string-concatenation-vs-stringbuilder-vs-string-format-performance

But a red flag :- Please avoid using String.format() when possible. It is unbelievably slow.

There are a many ways to concatenate strings. I do not think that there is a right way, as the right way usually depends on your use case. Some methods are very good for bulk operations, while others are very good at concatenating individual variables.

This Comparison Link Might help in thorough Analysis

Pramod S. Nikam
  • 4,271
  • 4
  • 38
  • 62