Java compilers have the implementation for +. The Javadocs says:
The Java language provides special support for the string
concatenation operator ( + ), and for conversion of other objects to
strings. String concatenation is implemented through the
StringBuilder(or StringBuffer) class and its append method. String
conversions are implemented through the method toString, defined by
Object and inherited by all classes in Java. For additional
information on string concatenation and conversion, see Gosling, Joy,
and Steele, The Java Language Specification.
You can try to check this:
public static void main(String[] args) {
String s1 = "s1";
String s2 = "s2";
String s3 = s1 + s2;
String s4 = new StringBuilder(s1).append(s2).toString();
}
The above code generates the same bytecode for + and when using StringBuilder:
L0
LINENUMBER 23 L0
LDC "s1"
ASTORE 1
L1
LINENUMBER 24 L1
LDC "s2"
ASTORE 2
// s3 = s1 + s2
L2
LINENUMBER 25 L2
NEW java/lang/StringBuilder
DUP
ALOAD 1
INVOKESTATIC java/lang/String.valueOf(Ljava/lang/Object;)Ljava/lang/String;
INVOKESPECIAL java/lang/StringBuilder.<init>(Ljava/lang/String;)V
ALOAD 2
INVOKEVIRTUAL java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString()Ljava/lang/String;
ASTORE 3
// s4 = new StringBuilder(s1).append(s2).toString()
L3
LINENUMBER 26 L3
NEW java/lang/StringBuilder
DUP
ALOAD 1
INVOKESPECIAL java/lang/StringBuilder.<init>(Ljava/lang/String;)V
ALOAD 2
INVOKEVIRTUAL java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString()Ljava/lang/String;
ASTORE 4
L4
LINENUMBER 27 L4
RETURN
+
specified forint
? – gronostaj 18 hours ago+
is recognised by the compiler as well.int i= 2+3
will be replaced byint i=5
. In case the value of int cannot be determined at compile time, then there are instructions likeiadd
which are used in place of+
– TheLostMind 17 hours ago