I need some help, a hint, ... figuring out how to add spaces to the front of a string without creating a string of spaces and then concatenating the string of spaces to the string. I used the following code, but was nitpick for not modifying the string moveIt only.
Pete, I have been reading about the String class in the JLS (4.3.3 The Class String 15.18.1). It looks like when a String is concatenated using the "+" a reference to the newly created String with the two operands concatenated is the result. So you end up with a new String obj. However, it also says that the compiler might implement StringBuffer (mutable) to optimize the string concatenation by reducing the number of intermediate Strings. Also in the API specs it says that for string concatenation operator(+) the StringBuffer and its append() method are implemented. Would I be gaining anything by directly using a mutable class? It seems like I'm getting a mutable class by using the "+" on the String obj.
Richard, that is true, but it always turns it back into a String. So if you say this: String a += b; That JVM does something like this: StringBuffer temp = new StringBuffer(a); temp.append(b); String a = temp.toString; If you are only doing this once, it is not a big deal, I would just use a String, but if you have this in a loop, and have the potential for doing it many times, you will get better performance by using a StringBuffer and then after the loop, converting it back to a String. Bill