1

Here is my String array containing the following:

"message" "player" "how" "are" "you"

I am wanting to join the "how" "are" "you" part of the String[] and I am currently doing the following:

String msg = "";

for (int i = 2; i < args.length; i++)
{
    msg = msg + args[i] + " ";
}

Util.messagePlayer(player, msg);

So my question is, is there a better/more efficient way of doing this?

2 Answers2

1

Yes, there is a better way, everytime you are iterating that array, new String objects are getting created(because Strings are immutable), however this one is a short String, so the efficiency loss is not that considerable,still try to use StringBuilder instead

StringBuilder msg = new StringBuilder();

for (int i = 2; i < args.length; i++)
{
    msg.append(args[i] + " ");
}
Util.messagePlayer(player, msg.toString);

For complete details, StringBuilder vs String concatenation in toString() in Java

Community
  • 1
  • 1
nobalG
  • 4,544
  • 3
  • 34
  • 72
  • Works, although msg needs to be: `StringBuilder msg = new StringBuilder();` –  Dec 29 '16 at 11:51
0

String objects are immutable ones in Java, hence every time you concatenate two strings, you are creating a new Object this is costly.

Instead, you can use a StringBuilder.

More about how to use it is well described here: Correct way to use StringBuilder

Community
  • 1
  • 1
sandor
  • 643
  • 6
  • 16