I was having a discussion about usage of Strings and StringBuffers in Java. How many objects are created in each of these two examples?
Ex 1:
String s = "a";
s = s + "b";
s = s + "c";
Ex 2:
StringBuilder sb = new StringBuilder("a");
sb.append("b");
sb.append("c");
In my opinion, Ex 1 will create 5 and Ex 2 will create 4 objects.
You can determine the answer by analyzing the java bytecode (use
javap -c). Example 1 creates twoStringBuilderobjects (see line #4) and twoStringobjects (see line #7), while example 2 creates oneStringBuilderobject (see line #2).Note that you must also take the
char[]objects into account (since arrays are objects in Java).StringandStringBuilderobjects are both implemented using an underlyingchar[]. Thus, example 1 creates eight objects and example 2 creates two objects.Example 1:
Example 2: