# Recursive Permutation in Java

Saurabh | Mar 13, 2010 | Comments 4

Finding all the permutations for any given set of items has always been an area of interest for programmers. A very simple algorithm for finding all the permutations, the Bell Algorithm and the C code implementation of that algorithm has already been presented. However the initial solution was provided using iteration.

Here the java code for permutation is presented using recursive routine.

```
import java.io.*;
public class permutation {
public static void main(String args[]) throws IOException{
String str;
System.out.println("Enter the initial string");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
System.out.println("Permutations are :");
permute("", str);
}
public static void permute(String beginningString, String endingString) {
if (endingString.length() <= 1)
System.out.println(beginningString + endingString);
else
for (int i = 0; i < endingString.length(); i++) {
try {
String newString = endingString.substring(0, i) + endingString.substring(i + 1);
permute(beginningString + endingString.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
```

**About the Author**: Software Engineer - Advanced Search & Recommendation at Rovi

cool, i m trying the same logic. but struggling on the codes.

ooops.

Thanks, It was really helpful.

I needed the resultset to be unique so I stored the result into HashSet instead of printing it directly.

not understood anything …plzzz expln clearly.

Hi Priti,

In case you are having trouble in understanding the recursive approach, you can check out this post which is more explanatory and uses a more efficient algorithm