method A String str = "["; //one string obj has been created in String pool String str2 = str + "hallo"; //internally translate to //new StringBuffer(str).append("hallo").toString()
vs method B String str2 = "[" + "hallo"; //internally translate to //new StringBuffer("[").append("hallo").toString();
So, does it means that method A will be creating more objects than method B? Someone please help to explain......
[ March 26, 2003: Message edited by: MoonChinn Goh ]
posted 12 years ago
Yes..method A will create more objects that method B.. If u do multiple concatenation in a single line, the append() method of the StringBuffer class is called multiple times. But only two objects are created- StringBuffer and String objects. When u do the concatenation over multiple lines, a new String object is created everytime and for each of that a StringBuffer object is created. Performance-wise additional method calls are far better than additinal object creation and their subsequent garbage collection.