Search code examples
javastringstringbuffer

Create a string with n characters


Is there a way in Java to create a string with a specified number of a specified character? In my case, I would need to create a string with ten spaces. My current code is:

final StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
   outputBuffer.append(" ");
}
return outputBuffer.toString();

Is there a better way to accomplish the same thing? In particular, I'd like something that is fast (in terms of execution).


Solution

  • The for loop will be optimized by the compiler. In such cases like yours you don't need to care about optimization on your own. Trust the compiler.

    BTW, if there is a way to create a string with n space characters, than it's coded the same way like you just did.