Java operator `+` and `StringBuilder.append`

It was said that when I use the operator +

for concat String

it is later converted to StringBuilder.append

, but when I ran the Java Decompiler GUI and opened it 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's wrong? I compiled it withjavac MainClass.java

+3


source to share


1 answer


Most decompilers will automatically convert compiler-generated sequences StringBuilder

to string concatenation using +

.

One of the few that is not there is Krakatau . If you decompile the class with Krakatau, you end up with 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, there is a code StringBuilder

. You can also check dismantling.

.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

      

+4


source







All Articles