4

In Java 8, I wrote some sample code.

String s1 = "Hello";  
String s2 = "world";  
String s3 = s1 + s2;  

After decompiling .class file I found that 3rd statement

 String s3 = s1 + s2;  

replaced by

 String s3 = new StringBuilder(s1).append(s2).toString();

Does it mean that There is no longer need to use explicit StringBuilder for Optimization and just use '+' operator instead of?

shubham12511
  • 620
  • 1
  • 9
  • 25
  • "*Does it mean that There is no longer need to use explicit StringBuilder*" - No, javac uses it in such trivial cases only. In a loop, you still need to use `StringBuilder` youself. – maaartinus Jun 30 '16 at 12:59
  • Yes It is right, I wrote some sample program and decompile it and got to know that in loop we need StringBuilder. – shubham12511 Jul 01 '16 at 04:48

1 Answers1

8

Yes. Actually, this optimization had been done in Java 6. See Bruce Eckel's "Thinking in Java" 4th edition pp.356-359 for details

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36