In  this tutorial, we will see “How to Print all Permutations of a String in Java”

Print all permutations of string in java

Java – How to Print all Permutations of a String? Share on X

/** 
 * Print All Permutations of String in Java 
 * @author Deepak Verma 
 */

import java.util.Scanner;

public class Print_All_Permutations_Of_String_Java {

	public static void main(String[] args) {
		try (var scan = new Scanner(System.in)) {
			System.out.println("Enter the string to Permute: ");
			String str = scan.nextLine();
			int n = str.length();
			permuteString(str, 0, n - 1);
		}
	}
	
	public static void permuteString(String str, int l, int r) {
		if (l == r) {
			System.out.println(str);
		} else {
			for (int i = l; i <= r; i++) {
				str = swapChar(str, l, i);
				permuteString(str, l + 1, r);
				str = swapChar(str, l, i);
			}
		}
	}

	public static String swapChar(String str, int i, int j) {
		char[] charArray = str.toCharArray();
		char temp = charArray[i];
		charArray[i] = charArray[j];
		charArray[j] = temp;
		return String.valueOf(charArray);
	}

}

 

Output:

Enter the string to Permute: 
Tech
Tech
Tehc
Tceh
Tche
Thce
Thec
eTch
eThc
ecTh
echT
ehcT
ehTc
ceTh
cehT
cTeh
cThe
chTe
cheT
hecT
heTc
hceT
hcTe
hTce
hTec

check if text or string present in a file using java 8

 

Print all permutations of string in java

Java – How to Print all Permutations of a String? Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts