How to Shuffle a Word in Java

Shuffling characters in a word involves randomly swapping letters in the word. It is used in vocabulary games such as Jumble game to improve English language skills.

The following Java program shuffles a given word. The shuffling is achieved by randomly swapping characters 10 times (just an arbitrary number). It can be improved by replacing the shuffle count 10 by another random number. Note that this algorithm is not the best algorithm for shuffling. A better approach will be swapping every character in the word by another random character in the word or using well known shuffling algorithms such as Fisher-Yates algorithm or Durstenfeld algorithm.

import java.util.concurrent.ThreadLocalRandom;

/**
 * Java program to shuffle a word randomly 
 */
public class ShuffleWord {

    public static void main(String[] args) {
        ShuffleWord sw = new ShuffleWord();
        String word = "Hello";
        String shuffled = sw.shuffle(word);
        System.out.println("Original word:"+word);
        System.out.println("Shuffled word:"+shuffled);
    }

    /**
     * Shuffles a given word. Randomly swaps characters 10 times.
     * @param word
     * @return 
     */
    private String shuffle(String word) {
        String shuffledWord = word; // start with original
        int wordSize = word.length();
        int shuffleCount = 10; // let us randomly shuffle letters 10 times
        for(int i=0;i<shuffleCount;i++) {
            //swap letters in two indexes
            int position1 = ThreadLocalRandom.current().nextInt(0, wordSize);
            int position2 = ThreadLocalRandom.current().nextInt(0, wordSize);
            shuffledWord = swapCharacters(shuffledWord,position1,position2);
        }
        return shuffledWord;
    }
    
    /**
     * Swaps characters in a string using the given character positions
     * @param shuffledWord
     * @param position1
     * @param position2
     * @return 
     */
    private String swapCharacters(String shuffledWord, int position1, int position2) {
        char[] charArray = shuffledWord.toCharArray();
        // Replace with a "swap" function, if desired:
        char temp = charArray[position1];
        charArray[position1] = charArray[position2];
        charArray[position2] = temp;
        return new String(charArray);
    }
}