String vs StringBuilder - Number of objects
java, string, stringbuilder
Solution
Your first analysis is correct, but second snippet creates only one String Object. Because, it's a compile time concatenation of Strings literals.
Problem
I came across two code snippets which were creating a query to be executed further: ``` 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 the snippets create 4 objects. First snippet creates a StringBuilder object and 3 string objects while the second snippet creates 4 String objects. Is my analysis correct? How snippet one is more efficient than snippet 2?