String Permutations

This program prints all possible permutations of a given string.
It uses recursion and backtracking logic with a swap method.

Java Code
public class Main {
    public static void main(String[] args) {
        String str = "ab";
        int length = str.length();

        // Start recursive permutation generation
        permute(str, 0, length - 1);
    }

    // Recursive method to generate permutations
    private static void permute(String str, int left, int right) {
        if (left == right) {
            System.out.println(str); // A complete permutation
        } else {
            for (int i = left; i <= right; i++) {
                str = swap(str, left, i);     // Swap current character
                permute(str, left + 1, right); // Recurse
                str = swap(str, left, i);     // Backtrack
            }
        }
    }

    // Swap characters in a string and return the new string
    private static String swap(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
Permutations of "ab":
ab
ba