6

My method below needs to return a String concatenated from strings.

StringBuilder sb = new StringBuilder();
sb.append("count: ").append(this.count()).append( "\n");

return sb.toString();

In IntelliJ, the Code Inspection suggests me to replace this StringBuilder with a String like below:

String sb = "count: " + this.count() + "\n";
return sb

My impression is that StringBuilder should be used with the append method, to replace string concatenation with the plus sign. Does this code inspection suggestion make sense in IntelliJ?

2

1 Answer 1

7

You are correct in your presumptions that most IntelliJ inspections encourage you to do things in a "better" way.

However, this is not always the case. Especially where some inspections work "both ways" -> you'll have to exercise your own judgement about what is "better".

In this case, if you start with a normal concatenated string:

    return "count: " + count + "\n";

There are a few inspections available - put cursor on "count: " and hit alt-enter:

  1. Replace '+' with String.format()
  2. Replace '+' with StringBuilder.append()
  3. Replace '+' with java.text.MessageFormat.format()

If you choose option (2), you get this:

    return new StringBuilder().append("count: ").append(count).append("\n").toString();

Now, you can use alt-enter again to choose "Replace StringBuilder with String" reverse the change.

In this case, you have discovered an inspection / refactoring that is bi-directional: it works both ways. Other refactorings (such as "Encapsulate") work only one way.

As for what is "better" - you have to weigh up the performance of StringBuilder versus readability and simplicity, and make that judgement yourself - IntelliJ is just providing handy inspections to assist you ;)

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for side stepping the question headline (which is addressed in numerous other places :) and instead addressing this aspect of it: "Does this code inspection suggestion make sense ...?" very neatly.
@glitch except it does not really answer the question because it does not explain when StringBuilder should be used, which is the reason why OP is confused.
Aldo the description of the inspection in IntelliJ clearly says "Using a String concatenation makes the code shorter and simpler. This inspection only reports when the resulting concatenation is at least as efficient or more efficient than the original StringBuffer or StringBuilder code. "
@Meo the performance implications are explained for example here: stackoverflow.com/questions/1532461/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.