Finding all upper/lower case combinations of a word For every word there are 2^n different ways of writing the word if you take into account upper/lower case letters. Eg for "word" we can write;


word
Word
wOrd
WOrd
woRd
WoRd
etc


I've written this code to calculate all the combinations. Is there any way I can improve the performance? Profiling tells me that this method takes 99.9% of the execution time of my program (which measures password strength).

String word = "word";
int combinations = 1 &lt;&lt; word.length();   

for (int i=0; i&lt;combinations; i++) {
  StringBuilder buf = new StringBuilder(word);
  for (int j=0; j&lt;word.length(); j++) {
    if ((i &amp; 1&lt;&lt;j) != 0) {
      String s = word.substring(j, j+1).toUpperCase();
      buf.replace(j, j+1, s);
    }
  }
  System.out.println(buf);
}
public static void comb(String word) {
    int combinations = 1 &lt;&lt; word.length();
    char[][] chars = { word.toLowerCase().toCharArray(),
                       word.toUpperCase().toCharArray() };
    char[] result = new char[word.length()]; 

    for (int i = 0; i &lt; combinations; i++) {
        for (int j = 0; j &lt; word.length(); j++) {
            result[j] = chars[(i &gt;&gt; j) &amp; 1][j];
        }
        System.out.println(new String(result));
    }
}


[Edit]

I did some profiling, and my version seems slightly better, and the following version is even a little bit faster:

public static void comb(String word) {
    word = word.toLowerCase();    
    int combinations = 1 &lt;&lt; word.length();
    for (int i = 0; i &lt; combinations; i++) {
        char[] result = word.toCharArray();
        for (int j = 0; j &lt; word.length(); j++) {
            if (((i &gt;&gt; j) &amp; 1) == 1 ) {
               result[j] = Character.toUpperCase(word.charAt(j));
            }   
        }
        System.out.println(new String(result));
    }
}    


However, all versions so far are in the same ballpark and won't change something substantial, because System.out.println dominates the performance.

[Edit 2]

The algorithm really doesn't matter much, the System.out.println impact is too heavy. Collection everything in a StringBuilder and calling System.out.println doesn't help either. However, quite surprisingly my profiler tells me that this simple recursive version performs best:

public static void comb4(String word) {
    comb4(word,new char[word.length()],0);
}    

private static void comb4(String word, char[] accu, int index) {
    if(index == word.length()) {
        System.out.println(accu);
    } else {
        char ch = word.charAt(index);
        accu[index] = Character.toLowerCase(ch);
        comb4(word, accu , index+1);
        accu[index] = Character.toUpperCase(ch);
        comb4(word, accu, index+1);
    }
}