Search code examples
javadecompiler

java operator `+` and `StringBuilder.append`


It was said that when I use + operator to concat String it later transforms into StringBuilder.append but when I ran Java Decompiler GUI and opened MainClass.class there was

public class MainClass
{
  public static void main(String[] paramArrayOfString)
  {
    String str1 = "abc";
    String str2 = "def";

    String str3 = str1 + str2;
  }
}

when the original was

public class MainClass {

    public static void main(String[] args) {

        String val1 = "abc";
        String val2 = "def";

        String res = val1 + val2;

    }
}

What is wrong? I compiled it using javac MainClass.java


Solution

  • Most decompilers will automatically transform the compiler generated StringBuilder sequences back into string concatenation with +.

    One of the few that doesn't is Krakatau. If you decompile the class with Krakatau, you'll get something like

    public class MainClass {
        public MainClass()
        {
            super();
        }
    
        public static void main(String[] a)
        {
            new StringBuilder().append("abc").append("def").toString();
        }
    }
    

    So as you can see, the StringBuilder code is there. You can also look at the disassembly to be sure.

    .version 51 0
    .source MainClass.java
    .class super public MainClass
    .super java/lang/Object
    
    
    .method public <init> : ()V
        ; method code size: 5 bytes
        .limit stack 1
        .limit locals 1
        aload_0
        invokespecial java/lang/Object <init> ()V
        return
    .end method
    
    .method static public main : ([Ljava/lang/String;)V
        ; method code size: 26 bytes
        .limit stack 2
        .limit locals 4
        ldc 'abc'
        astore_1
        ldc 'def'
        astore_2
        new java/lang/StringBuilder
        dup
        invokespecial java/lang/StringBuilder <init> ()V
        aload_1
        invokevirtual java/lang/StringBuilder append (Ljava/lang/String;)Ljava/lang/StringBuilder;
        aload_2
        invokevirtual java/lang/StringBuilder append (Ljava/lang/String;)Ljava/lang/StringBuilder;
        invokevirtual java/lang/StringBuilder toString ()Ljava/lang/String;
        astore_3
        return
    .end method