What is the complexity of this simple piece of code?

This seems to be a question of mislead, because I happened to read that book just now. This part of text in the book is a typo! Here is the context: =================================================================== Question: What is the running time of this code? 1 public String makeSentence(String[] words) { 2 StringBuffer sentence = new StringBuffer(); 3 for … Read more

What is the difference between String and StringBuffer in Java?

String is used to manipulate character strings that cannot be changed (read-only and immutable). StringBuffer is used to represent characters that can be modified. Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable. You can … Read more

Create a string with n characters

Likely the shortest code using the String API, exclusively: String space10 = new String(new char[10]).replace(‘\0’, ‘ ‘); System.out.println(“[” + space10 + “]”); // prints “[ ]” As a method, without directly instantiating char: import java.nio.CharBuffer; /** * Creates a string of spaces that is ‘spaces’ spaces long. * * @param spaces The number of spaces … Read more