Like most other programming languages, the Java language allows the use of + to concatenate two strings.

String name = "stephen";
String foo = "Hey, " + name;
Copy the code

No error is reported when we concatenate a string with a non-string value:

String name = "Stephen";
int age = 25;
String foo = name + age; // The result is Stephen25
Copy the code

The reason for this is that when one value to the left and right of the + operator is a string, the other value is attempted to be converted to a string.

String conversion mechanism

Before we look at String concatenation operators, let’s look at String Conversion.

Any type may be converted to type String by string conversion.

If the value x is a primitive data type T, it is first converted to a reference value before the string is converted. Here are a few examples:

• If T is Boolean, it will be wrapped in new Boolean(x);

• If T is a char, it is encapsulated with new Character(x);

• If T is byte, short, or int, it will be wrapped with a new Integer(x);

We know that Java has a wrapper class for primitive data types (such as int for Integer objects), so that the value X for each of the underlying data types becomes a reference to an object.

Why do you do that? For uniformity, all values are unified object references when we convert the underlying data type to an instance of the corresponding wrapper class.

This is when the actual string conversion begins. We need to consider two cases: null and non-null.

If x is null, the resulting string conversion is a string null;

Otherwise, the no-argument method of the object’s toString() is called.

Let’s take a look at the latter:

Of all the Java superclasses Object, one important method is the toString method, which returns a string representing the value of the Object. ToString is defined in the Object class as follows:

public String toString(a) {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Copy the code

This method returns the class name and hash code of the object. If a class does not override the toString method, the toString method of its parent class is called by default, and our value x is always an object value, so there must be a toString method that can be called and printed out. If the toString call returns a null value, the string null is used instead.

String concater

When one of the expressions to the left and right of the + operator is a string, the other value is converted at run time.

It is important to note that the + operator is also used as an arithmetic operator, so you should pay attention to the precedence of multiple values, as in the following example:

String a = 1 + 2 + " equals 3";
String b = "12 eqauls " + 1 + 2;
Copy the code

The result of variable A is 3 equals 3, and the result of variable B is 12 equals 12.

Some of you might have a problem with this, but just to clarify, the first case is based on the precedence of 1+2 so the + operator is the arithmetic operator, so the result is 3, and then “equals 3″, and since 3 +” equals 3″ has a string, So the + operator is the string concatenation operator.

At runtime, the Java compiler will generally use similar StringBuffer/StringBuilder this way with a buffer to reduce by performing expression created when the number of intermediate String objects, so as to improve application performance.

Java disassembler javap

Suppose you have the following code:

public class Demo {
    public static void main(String[] args) {
        int i = 10;
        String words = "stephen"+ i; }}Copy the code

Then compile and disassemble:

javac Demo.java
javap -c Demo
Copy the code

You can get the following:

Compiled from "Demo.java"
public class Demo {
  public Demo();
    Code:
       0: aload_0
       1: invokespecial #1 // Method java/lang/Object."
      
       ":()V
      
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: bipush        10
       2: istore_1
       3: new           #2 // class java/lang/StringBuilder
       6: dup
       7: invokespecial #3 // Method java/lang/StringBuilder."
      
       ":()V
      
      10: ldc           #4 // String stephen
      12: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;) Ljava/lang/StringBuilder;
      15: iload_1
      16: invokevirtual #6 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
      19: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      22: astore_2
      23: return
}
Copy the code

We can see that the Java compiler creates a StringBuilder object when executing the expression of the string concatenation operator, concatenates the string Stephen (append) to the left of the operator, and then concatenates the integer 10 to the right. The toString method of StringBuilder is then called to return the result.

What if we’re concatenating an object?

public class Demo {
    public static void main(String[] args) {
        Demo obj = new Demo();
        String words = obj + "stephen";
    }

    @Override
    public String toString(a) {
        return "App{}"; }}Copy the code

As practice, we find the Method of Java/lang/StringBuilder. Append: (Ljava/lang/Object) StringBuilder calls append(Object obj).

public StringBuilder append(Object obj) {
    return append(String.valueOf(obj));
}
Copy the code

ValueOf (obj) ¶

public static String valueOf(Object obj) {
    return (obj == null)?"null" : obj.toString();
}
Copy the code

That is, the toString() method of the object is called.

If a string is converted to a primitive type, then the toString method is called. If a string is converted to a primitive type, then the toString method is called.

The implementation is essentially the same, but the Java compiler uses StringBuilder to improve performance (reduce the cost of creating intermediate strings, etc.). If you’re interested, you can trace the toString method of the Integer wrapper class for yourself, which is almost identical to the append(int I) method of StringBuilder.

Refer to the link

• String Concatenation Operator +

• String Conversion