Java - Write code to Repeat a string n times to form a new string.

Requirements

Write code to Repeat a string n times to form a new string.

Demo

/*
 * Copyright (c) 2001-2002, Marco Hunsicker. All rights reserved.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 *///from  w  w w. ja  va 2s  .  c  om
 
//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        int repeat = 4;
        System.out.println(repeat(str, repeat));
    }

    /**
     * Repeat a string n times to form a new string.
     *
     * @param str String to repeat
     * @param repeat int number of times to repeat
     *
     * @return String with repeated string
     */
    public static String repeat(String str, int repeat) {
        StringBuffer buffer = new StringBuffer(repeat * str.length());

        for (int i = 0; i < repeat; i++) {
            buffer.append(str);
        }

        return buffer.toString();
    }
}