How to Generate Anagrams in Java

In this instructional exercise, we will find how to generate anagrams of a string in Java.  We can also say that we will write a Java program to print all permutations of a given string.

First understand what Anagram is:-

An Anagram is a re-arranged word or expression framed by modifying the letters of an alternate word or expression, regularly utilizing all the first letters precisely once.

If you don’t know how to find the anagram of any string through java program then you are at the right place to know your problem’s solution.

Java Program to Generate Anagram

Java Program to achieve the goal:-

We have taken a string and trying to get the anagram of the input string.

Here is a program to generate anagrams of a string in Java.

public class Anagram { 
    public static void main(String[] args) 
        String str = "SKR"; 
        System.out.println("String is:-"+str);
        System.out.println("Anagram of the given string is:-");
        int size = str.length(); 
        Anagram a = new Anagram(); 
        a.anagm(str, 0, size - 1); 
    private void anagm(String str, int start, int end) 
        if (start == end) 
        else { 
            for (int i = start; i <= end; i++) { 
                str = swap(str, start, i); 
                anagm(str, start + 1, end); 
                str = swap(str, start, i); 
    public String swap(String a, int i, int j) 
        char temp; 
        char[] charArray = a.toCharArray(); 
        temp = charArray[i]; 
        charArray[i] = charArray[j]; 
        charArray[j] = temp; 
        return String.valueOf(charArray); 

The Output of this program is:-

String is:-SKR
Anagram of the given string is:-

This is how we can print all permutations of a given string in Java.

Read more Java tutorials:

Leave a Reply

Your email address will not be published. Required fields are marked *