Java - Write code to create a string by repeating a string certain times

Requirements

Write code to create a string by repeating a string certain times

Demo

//package com.book2s;

import java.util.Arrays;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        int times = 42;
        System.out.println(repeat(string, times));
    }//from  ww  w  . ja  v a2s  . c  om

    public static String repeat(String string, int times) {
        StringBuffer buf = new StringBuffer(string.length() * times);
        for (int i = 0; i < times; i++)
            buf.append(string);
        return buf.toString();
    }

    public static String repeat(char character, int times) {
        char[] buffer = new char[times];
        Arrays.fill(buffer, character);
        return new String(buffer);
    }

    public static String toString(Object[] array) {
        int len = array.length;
        if (len == 0)
            return "";
        StringBuffer buf = new StringBuffer(len * 12);
        for (int i = 0; i < len - 1; i++) {
            buf.append(array[i]).append(", ");
        }
        return buf.append(array[len - 1]).toString();
    }
}

Related Exercise