Usage of StringBuilder for returning copies of a string Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front:

frontTimes("Chocolate", 2) → "ChoCho"
frontTimes("Chocolate", 3) → "ChoChoCho"
frontTimes("Abc", 3) → "AbcAbcAbc"
frontTimes("X", 3) → "XXX"



I've solved above problem using following code but I'm using a new StringBuilder to store intermediate string result. Does it really needed can I optimize and remove the for loop in the else?

public String frontTimes(String str, int n) {

        StringBuilder sb = new StringBuilder(str);
        StringBuilder newsb = new StringBuilder();

        if(sb.length() &gt;= 3)
        {
            for(int i = 0; i &lt; n; i++)
            {
                newsb.append(sb.substring(0,3));
            }

            return newsb.toString(); 
        }
        else
        {
            for(int i = 0; i &lt; n; i++)
            {
                newsb.append(sb.toString());
            }

            return newsb.toString();

        }

    }
I'd just like to make a slight change to the code. When you are instantiating a StringBuilder, you have the opportunity to specify the capacity of it. Using this constructor, we can avoid having it resized more than necessary.

public String frontTimes(String str, int n) {
    StringBuilder stringBuilder = new StringBuilder(3 * n);
    if (str.length() &gt; 3) {
        str = str.substring(0, 3);
    }
    for (int i = 0; i &lt; n; i++) {
        stringBuilder.append(str);
    }
    return stringBuilder.toString();
}


Note how many times that 3 is declared? Would be better to extract that to a constant, or even better, a parameter. And with a few other changes to the above (as suggested by @rolfl in chat):

public String frontTimes(final String str, final int frontLength, final int times) {
    String copyString = str.length() &gt; frontLength ? str.substring(0, frontLength) : str;
    StringBuilder stringBuilder = new StringBuilder(copyString.length() * times);
    for (int i = 0; i &lt; times; i++) {
        stringBuilder.append(copyString);
    }
    return stringBuilder.toString();
}