Open In App

How to Shuffle Characters in a String in Java?

In this article, we will learn how to shuffle characters in a String by using Java programming. For this, we have taken a String value as input and the method is available in java.util package and this method takes a list as input.

Steps to shuffle characters in a String in Java

Java Program Shuffle characters in a String

Here, we have taken one Java class. After that, in the main class, we have created shuffleString(String input). This method takes one String value as an argument. After that this String value is converted into a character array then shuffle the characters by using the Collections.shuffle method. This result appends to the StringBuilder class object and finally prints the required result.

Below is the implementation of the above-mentioned topic:




// Java Program to demonstrate
// Shuffling characters in a String
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
  
// Driver Class
public class ShuffleStringExample {
    public static String shuffleString(String input) {
        
        // Convert String to a list of Characters
        List<Character> characters = new ArrayList<>();
        for (char c : input.toCharArray()) {
            characters.add(c);
        }
  
        // Shuffle the list
        Collections.shuffle(characters);
  
        // Convert the list back to String
        StringBuilder shuffledString = new StringBuilder();
        for (char c : characters) {
            shuffledString.append(c);
        }
  
        return shuffledString.toString();
    }
  
    public static void main(String[] args) {
        // Example usage
        String originalString = "GeeksForGeeks";
        String shuffledString = shuffleString(originalString);
  
        System.out.println("Original String: " + originalString);
        System.out.println("Shuffled String: " + shuffledString);
    }
}

Output in console:

Explanation of the above Program:


Article Tags :