Java - String Concatenation Operator + and StringBuilder

Introduction

You can use the + operator to concatenate a strings, and a primitive type value or an object to another string.

For example,

String str = "X" + "Y" + 12.56;

To optimize the string concatenation operation, the compiler replaces the string concatenation by a statement, which uses a StringBuilder.

The compiler replaces the above statement with the following one:

String str = new StringBuilder().append("X").append("Y").append(12.56).toString();

toString() method at the end of this statement is used to convert the final content of a StringBuilder to a String.

append() method of StringBuilder returns a reference to itself.

Demo

public class Main {
  public static void main(String[] args) {
    String str = "X" + "Y" + 12.56;
    System.out.println(str);//from  w w  w.j ava2  s  .c  o  m
    str = new StringBuilder().append("X").append("Y").append(12.56).toString();
    System.out.println(str);
  }
}

Result

Related Topic