This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
HI all Suppose i have 3 variables. If i write like this StringBUffer sb = new StringBuffer("["); sb.append("',"+variable1+",'"); sb.append("',"+variable2+",'"); sb.append("',"+variable3+",'"); Is this code creating new string objects because of using + inside append.
Failures are practice shoots for success.
Before the StringBuffer.append method is called the supplied argument has to be evaluated. In your case the supplied argument is "',"+variable1+",'" which when evaluated will cause new String objects to be created.
The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String. To discover why this is the case, we must examine the generated bytecode from our two examples. The bytecode for the example using String looks like this:
The bytecode at locations 0 through 9 is executed for the first line of code, namely:
String str = new String("Stanford ");
Then, the bytecode at location 10 through 29 is executed for the concatenation:
str += "Lost!!";
Things get interesting here. The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.
After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done with the call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are very expensive.
In summary, the two lines of code above result in the creation of three objects:
1. A String object at location 0 2. A StringBuffer object at location 10 3. A String object at location 26