String vs StringBuilder - number of objects

I came across two pieces of code that created a request for further execution:

StringBuilder stringBuilder = new StringBuilder(); 
stringBuilder.append("SELECT * FROM EMPLOYEE "); 
stringBuilder.append("WHERE SALARY > ? "); 
stringBuilder.append("GROUP BY DEPT");

and

String string = "SELECT * FROM EMPLOYEE " +
"WHERE SALARY > ? " +
"GROUP BY DEPT";

According to my analysis, both fragments create 4 objects. The first fragment creates a StringBuilder object and 3 string objects, and the second fragment creates 4 String objects. Is my analysis correct?

How effective is a snippet than fragment 2?

+3
source share
5 answers

Your first analysis is correct, but the second snippet creates only one String Object. Because it is a compilation of the time of String literals.

+8
source

Not really ...

1 StringBuilder 3 String (/ JVM). String , stringBuilder.toString().

1 String (/ JVM), . :

String string = "SELECT * FROM EMPLOYEE WHERE SALARY > ? GROUP BY DEPT";
+5

StringBuilder 4 .

String. 3 String , Java , , String , , String .

,

String string = "SELECT * FROM EMPLOYEE " +
"WHERE SALARY > ? " +
"GROUP BY DEPT";

String string = "SELECT * FROM EMPLOYEE WHERE SALARY > ? GROUP BY DEPT";
+3

, , concatenation (. operator), String . StringBuilder , .

0

1 . .

StringBuilder has better performance when combining mutable strings. For example, with your example:

StringBuilder stringBuilder = new StringBuilder(); 
stringBuilder.append("SELECT * FROM EMPLOYEE "); 
if(salary > 0) {
    stringBuilder.append("WHERE SALARY > ? "); 
}
if(group == true) {
    stringBuilder.append("GROUP BY DEPT");
}

String string = "SELECT * FROM EMPLOYEE ";
if(salary > 0) {
    string = string + "WHERE SALARY > ? ";
}
if(group == true) {
    string = = string + "GROUP BY DEPT";
}
0
source

All Articles