Below is the syntax highlighted version of Repeat.java
from §4.1 Performance.
/****************************************************************************** * Compilation: javac Repeat.java * Execution: java Repeat n * Dependencies: Stopwatch.java * * Create a string that contains n copies of the letter 'x'. * ******************************************************************************/ public class Repeat { public static String method1(int n) { if (n == 0) return ""; String temp = method1(n/2); if (n % 2 == 0) return temp + temp; else return temp + temp + "x"; } public static String method2(int n) { String s = ""; for (int i = 0; i < n; i++) s = s + "x"; return s; } public static String method3(int n) { if (n == 0) return ""; else if (n == 1) return "x"; else return method3(n/2) + method3(n - n/2); } public static String method4(int n) { char[] temp = new char[n]; for (int i = 0; i < n; i++) temp[i] = 'x'; return new String(temp); } public static void main(String[] args) { int n = Integer.parseInt(args[0]); Stopwatch timer = new Stopwatch(); String s = method4(n); // StdOut.println(method4(n)); StdOut.println("Elapsed time for method 4 = " + timer.elapsedTime()); timer = new Stopwatch(); s = method3(n); // StdOut.println(method3(n)); StdOut.println("Elapsed time for method 3 = " + timer.elapsedTime()); timer = new Stopwatch(); s = method1(n); // StdOut.println(method1(n)); StdOut.println("Elapsed time for method 1 = " + timer.elapsedTime()); timer = new Stopwatch(); s = method2(n); // StdOut.println(method2(n)); StdOut.println("Elapsed time for method 2 = " + timer.elapsedTime()); } }