0

When you decere like this . Are the instances created?

String string = "a"+"b"+"c";

Should it be declared like following?

StringBuilder sBuilder = new StringBuilder();
sBuilder.append("a");
sBuilder.append("b");
sBuilder.append("c");
puss
  • 7
  • 4

1 Answers1

1

For

String string = "a"+"b"+"c";

The compiler generates a complete string. The bytecode looks like this. Most compilers would do it this way since it is working with constants. Variable concatenation may be handled differently depending on the version of the JDK.

  0  ldc <String "abc"> [16]
  2  astore_1 [string]

So the following would be unnecessary overhead.

StringBuilder sBuilder = new StringBuilder();
sBuilder.append("a");
sBuilder.append("b");
sBuilder.append("c");

However, if you ever need to call append on the same StringBuilder object you can do the following:

StringBuilder sBuilder = new StringBuilder();
sBuilder.append("a").append("b").append("c");

StringBuilder.append returns its own instance.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • Older versions of the JDK would have compiled the string concatenation into a `StringBuilder` anyway, assuming not all the operands were string literals (as in the OP's example). Newer versions use [`StringConcatFactory`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/invoke/StringConcatFactory.html). The point being that `StringBuilder` really only makes sense if you're building a string in a loop or something similar. – Slaw Aug 07 '20 at 01:47
  • @slaw Thanks for the clarification. – WJS Aug 07 '20 at 01:48
  • Here's a relevant Q&A: [How is String concatenation implemented in Java 9?](https://stackoverflow.com/questions/46512888/how-is-string-concatenation-implemented-in-java-9). – Slaw Aug 07 '20 at 01:51
  • The golden rules 1) Never, ever optimize your code 2) If the profiler tells you to do it, break rule 1 – Jonathan Locke Aug 07 '20 at 03:45