Instead of string concatenation, another alternative is using String.format(...)
for formatting the message. Combining suggestions from other answers, I'd go with this implementation:
public class HelloWorld {
private final String message;
public HelloWorld(String name) {
this.message = String.format("Hello World, %s!", name);
}
@Override
public String toString() {
return message;
}
}
Since name
doesn't change, it's good to pre-format the message at construction time,
so that toString
can simply return it directly.
If you want to access the message directly, you could add a getter for it.
If you want to access the name, you might add a field and a getter for it.
But probably a "HelloWorld" object doesn't really need any accessors, does it?
UPDATE
The reason I suggested String.format
is because it was not mentioned by other answers, and it's often a useful alternative. It may be a matter of taste, a benefit of this approach is that a template string with placeholders + parameter list can be more readable than concatenation.
As per my discussion in comments with @vaxquis, be aware that the output of String.format
may depend on locale, for example when formatting dates and numbers. There is another version of String.format(Locale, String, ...)
that takes the Locale as the first parameter to ensure predictable output. (Without this parameter, the default locale is used.) This is especially important in applications intended to run in multiple locales, such as Android apps. For this reason, Android linters flag a warning for uses without a locale parameter.
In this particular example, there are no such concerns, because we're not printing anything locale-sensitive (no dates, numbers). But it's good to be aware of this locale-sensitive behavior in situations where it can make a difference.