Turn Complexity into Code: Learn Permutation in Java with Examples

By Rohan Vats

Updated on Jul 21, 2025 | 11 min read | 8.03K+ views

Share:

Did you know? By 2025, over 90% of Fortune 500 companies are expected to use Java for their software development needs, underscoring its dominance in the enterprise sector.

Permutation in Java is the process of generating all possible ordered arrangements of a set of elements, where the order significantly affects the outcome. Understanding Java permutation techniques helps you tackle challenges in data structure problems, algorithm design, and combinatorial problems that require systematic exploration of sequences.

This blog explains the fundamentals of permutation in Java, practical approaches to creating permutations with examples.

Tired of rote memorization and theory-heavy Java lessons? upGrad’s Online Software Development courses help you learn concepts like Permutation in Java with hands-on examples and practical use cases. Gain 1:1 mentorship and connect with over 300 top tech hiring partners.

Understanding Permutation in Java: An Overview of Basics

A permutation in Java refers to an arrangement of objects in a specific order. For a particular set, the number of possible permutations is calculated based on how many objects are selected and their order of arrangement. When considering permutations, the order in which the objects appear is important. It is then used to calculate the number of ways to arrange or order items from a set.

To strengthen your skills in Java and other advanced technologies, check these leading programs:

Let’s break down permutation in Java mathematically to understand how it works.

Understanding Permutation in Mathematics

Permutation is a way to find out how many different ways you can arrange a certain number of items when the order matters. It answers questions like: "How many ways can I arrange 3 letters?" or "How many ways can I line up 5 people?"

The formula to calculate permutations is:

P ( n , r ) = ( n - r ) ! r !

Where, 

  • n! (n factorial) means multiplying all whole numbers from n down to 1. For example, 3! = 3 × 2 × 1 = 6.
  • n is the total number of items you have.
  • r is the number of items you want to arrange or select.

Breaking down the formula:

  • The numerator, n!n!, counts all the possible ways to arrange all n items.
  • The denominator, (n−r)!(n - r)!, removes the arrangements of the leftover items you aren’t arranging.

Example: How many ways can you arrange the letters in “ABD”?

  • Total letters, n = 3 (A, B, and D)
  • Number of letters to arrange, r = 3 (since you want to arrange all letters)

Using the formula:

P(3,3)=(3−3)!/3!​=0!/3!​

We know:

  • 3! = 3 × 2 × 1 = 6
  • 0! is defined as 1

This means there are 6 different ways to arrange the letters A, B, and D. This concept helps solve many problems where the order of arrangement matters, such as passwords, seating arrangements, or scheduling tasks.

Software Development Courses to upskill

Explore Software Development Courses for Career Progression

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Planning to ace coding interviews or build strong Java fundamentals? Strengthen your core skills with upGrad’s free Java Object-oriented Programming course. Learn key concepts, such as classes, objects, inheritance, and polymorphism, through practical programming examples.

Also Read: Permutation vs Combination: Difference between Permutation and Combination

Now that you’ve explored the basic concept of permutation in Java, let’s understand how to implement it using Java. 

Implementing Permutation in Java: Key Approaches You Should Know

You can solve permutation problems using three common approaches: recursion with backtracking, iterative methods, and sometimes a combination of both. These approaches help you build a deeper understanding of algorithmic thinking and are often asked in coding interviews. Using Java, you'll write logic that generates all possible arrangements of a given set of elements, whether for characters, numbers, or objects.

Let’s look at the implementations of permutation in Java using different approaches.

1. Recursion with Backtracking

This approach is widely used for its simplicity and clarity. Using recursion and backtracking, you systematically explore all possible arrangements of elements. It’s ideal for solving permutation problems in coding interviews and algorithmic challenges.

Sample Code:

import java.util.*;

public class PermutationRecursive {
    public static void permute(String str, String result) {
        if (str.length() == 0) {
            System.out.println(result);
            return;
        }

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            String remaining = str.substring(0, i) + str.substring(i + 1);
            permute(remaining, result + ch);
        }
    }

    public static void main(String[] args) {
        String input = "ABC";
        permute(input, "");
    }
}

Code Explanation:

  • The function calls itself recursively, reducing the string size each time it is invoked.
  • Each call selects one character and appends it to the result.
  • Backtracking ensures all possible orders are covered.

Output:

ABC
ACB
BAC
BCA
CAB
CBA

Want to crack coding interviews or strengthen your problem-solving skills? Join upGrad’s free Data Structures & Algorithms course. Learn essential concepts, such as arrays, stacks, trees, and graphs, through expert-led lessons and real-world examples.

Also Read: Permutation vs Combination: Discover the Crucial Differences Now!

2. Iterative Approach using Heap’s Algorithm

This approach is known for its efficiency and structured process. Using Heap’s algorithm, you iteratively generate all possible permutations through smart in-place swaps. It’s a great fit for performance-critical tasks and understanding iterative logic in Java.

Sample Code:

public class PermutationIterative {
    public static void heapPermutation(char[] arr, int size) {
        if (size == 1) {
            System.out.println(String.valueOf(arr));
            return;
        }

        for (int i = 0; i < size; i++) {
            heapPermutation(arr, size - 1);

            if (size % 2 == 1) {
                char temp = arr[0];
                arr[0] = arr[size - 1];
                arr[size - 1] = temp;
            } else {
                char temp = arr[i];
                arr[i] = arr[size - 1];
                arr[size - 1] = temp;
            }
        }
    }

    public static void main(String[] args) {
        char[] input = {'A', 'B', 'C'};
        heapPermutation(input, input.length);
    }
}

Code Explanation:

  • Heap’s Algorithm uses swapping to generate permutations.
  • It's efficient and avoids a recursion stack overflow for larger inputs.

Output:

ABC
BAC
CBA
BCA
CAB
ACB

3. Iterative Using Next Permutation (Lexicographic Order)

This approach is efficient and systematic, particularly when generating permutations in sorted or dictionary order. By following a well-defined algorithm, you iterate through each possible arrangement without recursion. It's handy in problems that require the next immediate permutation or ordered output.

Sample Code:

import java.util.Arrays;

public class PermutationNext {
    public static void main(String[] args) {
        String input = "ABC";
        char[] chars = input.toCharArray();
        Arrays.sort(chars);

        do {
            System.out.println(String.valueOf(chars));
        } while (nextPermutation(chars));
    }

    private static boolean nextPermutation(char[] arr) {
        int i = arr.length - 2;
        while (i >= 0 && arr[i] >= arr[i + 1]) i--;
        if (i < 0) return false;

        int j = arr.length - 1;
        while (arr[j] <= arr[i]) j--;

        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;

        Arrays.sort(arr, i + 1, arr.length);
        return true;
    }
}

Code Explanation:

  • This method finds the next lexicographically greater permutation.
  • Useful when you want to generate all permutations in sorted order.

Output:

ABC
ACB
BAC
BCA
CAB
CBA

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

New to Java or want to build a strong foundation in programming? Start your journey with upGrad’s free Core Java Basics course. Learn essential concepts like variables, data types, loops, and OOP principles through beginner-friendly lessons that prepare you for real-world coding and advanced Java topics.

Now that you've learned how permutations work and how to implement them in Java, it's time to apply that knowledge to real-world challenges.

Challenging Permutation Problems to Sharpen Your Java Skills

To truly master the concept, you need to solve problems that introduce complexity, such as handling duplicates, generating permutations for integers, or working with subsets. These problems test your Java skills but also help you think algorithmically and write optimized, interview-ready code.

Here are some classic and advanced permutation problems that you can try implementing in Java to enhance your coding skills.

Example 1: Six people participate in a skit. In how many ways can the first and second prizes be awarded?

In this example, you have to determine how many ways you can award the first and second prizes to six people. You have to find the permutations of 6 people taken 2 at a time. You can use the permutation formula to solve the problem.

Here, n = 6 (number of people) and r = 2 (prizes to be awarded).

Sample Code:

public class PermutationExample1 {

    // Method to calculate permutations (nPr) of n items taken r at a time
    public static int permutation(int n, int r) {
        return factorial(n) / factorial(n - r);  // P(n, r) = n! / (n - r)!
    }

    // Method to calculate factorial of a number
    public static int factorial(int num) {
        int result = 1;
        for (int i = 1; i <= num; i++) {
            result *= i;
        }
        return result;
    }

    public static void main(String[] args) {
        int n = 6;  // Total number of participants
        int r = 2;  // Number of prizes to be awarded

        // Calculate and display the number of permutations (ways to award prizes)
        int result = permutation(n, r);
        System.out.println("Total ways to award first and second prize: " + result);
    }
}

Code Explanation:

The Example class calculates the number of permutations (nPr) of n items taken r at a time, which is often used to determine the number of ways to award prizes in a competition.

  • Permutation Method:
    • The permutation(int n, int r) method calculates the number of permutations using the formula P(n, r) = n! / (n - r)!.
    • This formula gives the number of ways to choose r items from n items when the order of selection matters.
  • Factorial Method:
    • The factorial(int num) method calculates the factorial of a given number num. The factorial is calculated by multiplying all integers from 1 to num (i.e., num! = num * (num - 1) * ... * 1).
  • Main Execution:
    • In the main() method, n is set to 6 (total participants) and r is set to 2 (prizes to be awarded).
    • The permutation(n, r) method is called to calculate the number of ways to award the first and second prizes.
    • The result is printed, representing the total number of ways to award two prizes from six participants.

Output:

Total ways to award first and second prize: 30

Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced

Example 2: Find the permutation of a number n greater than the number itself.

In this example, let's assume you are given a number n (for example, 3), and you want to find the permutations of a number greater than n (for instance, 5). This means you have to calculate the permutations of 5 items taken 3 at a time.

Sample Code:

public class PermutationExample2 {

    // Method to calculate permutations (nPr)
    public static int permutation(int n, int r) {
        return factorial(n) / factorial(n - r);
    }

    // Method to calculate factorial
    public static int factorial(int num) {
        int result = 1;
        for (int i = 1; i <= num; i++) {
            result *= i;
        }
        return result;
    }

    public static void main(String[] args) {
        int n = 5;  // Total number of items
        int r = 3;  // Number of items to choose

        // Calculate and display the number of permutations
        int result = permutation(n, r);
        System.out.println("Total permutations of " + n + " items taken " + r + " at a time: " + result);
    }
}

Code Explanation:

The PermutationExample2 class calculates the number of permutations (nPr) of n items taken r at a time, which is useful for determining how many ways a subset of items can be chosen when the order matters.

  • Permutation Method:
    • The permutation(int n, int r) method calculates the number of permutations using the formula P(n, r) = n! / (n - r)!.
    • This formula is used to find the number of ways to choose r items from n items where the order of selection is important.
  • Factorial Method:
    • The factorial(int num) method calculates the factorial of a given number num. The factorial is calculated by multiplying all integers from 1 to num (i.e., num! = num * (num - 1) * ... * 1).
  • Main Execution:
    • In the main() method, n is set to 5 (total items available) and r is set to 3 (number of items to be chosen).
    • The permutation(n, r) method is called to calculate the number of ways to select 3 items from 5, taking the order into account.
    • The result is printed, representing the total number of permutations for choosing 3 items from 5.

Output:

Total permutations of 5 items taken 3 at a time: 60

Also Read: Top 135+ Java Interview Questions You Should Know in 2025

How Can upGrad Help You Advance Your Career in Java Development?

Permutations in Java help you build logic that handles complex arrangements, whether you're solving algorithmic problems, generating combinations, or designing smarter systems. From recursive methods to iterative logic, understanding how permutations work is key to becoming a stronger Java programmer.

To build confidence, apply these concepts by solving problems and coding challenges. Platforms like LeetCode and CodeChef are great for testing your problem-solving skills in these areas.

Many learners struggle to apply concepts like permutations in real code. upGrad’s software development courses help you build strong Java skills through hands-on projects and expert guidance. Here are some additional courses that will boost your programming language skills.

Feeling unsure about where to begin with your programming career? Connect with upGrad’s expert counselors or visit your nearest upGrad offline centre to explore a learning plan tailored to your goals. Transform your programming journey today with upGrad!

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Reference:
https://www.netguru.com/blog/is-java-still-used-in-2025

Frequently Asked Questions (FAQs)

1. What is the Best Method to Generate Permutation in Java?

The best method depends on the problem at hand. Recursive methods are easy to implement and work well for small datasets. However, for larger datasets or when avoiding duplicates is a concern, iterative and backtracking approaches are more efficient. These methods are faster and consume less memory when dealing with large input sizes.

2. Can I Use Java Libraries for Permutations?

Yes, Java provides built-in libraries like java.util.Collections and third-party libraries like Apache Commons Lang, which offer easy-to-use methods to generate permutations. These libraries simplify the process significantly by handling the internal logic, saving time and reducing the need for custom implementations.

3. How to Generate Permutations of Numbers or Other Data Types?

You can generate permutations of numbers or any other data types by treating them as arrays or lists. Once the data is represented as an array or list, you can apply the same permutation algorithms, like recursion or iteration, to generate all possible permutations of the elements, just as you would with strings.

4. What is the easiest way to generate a permutation in Java?

The easiest way is to use Java's built-in libraries such as java.util.Collections or Apache Commons Lang. These libraries offer pre-built methods for generating permutations, thereby eliminating the need to implement complex algorithms manually. They simplify the process and ensure that error-handling is taken care of automatically.

5. How can I generate permutations of a string in Java?

To generate permutations of a string in Java, first convert the string into a character array. Then, you can apply recursive or iterative permutation algorithms, such as backtracking or the next-permutation algorithm, to rearrange the characters and generate all possible permutations of the string.

6. How do I avoid duplicate permutations for strings with repeating characters?

To avoid duplicate permutations, first sort the string. Then, during the permutation generation, skip over repeated characters at the current recursion level to prevent processing the same character twice. This ensures that each generated permutation is unique, even when repeated characters are present in the input.

7. What is the difference between combination and permutation in Java?

Permutation in Java accounts for the order of elements, meaning that different orderings of the same elements are considered distinct. Combinations, on the other hand, do not consider order; different orderings of the same set of elements are treated as the same. Permutations are valid when order matters, while combinations are used when order is irrelevant.

8. What is backtracking, and how is it used for permutation in Java?

Backtracking is a technique where you explore all possible options and undo the last decision if it doesn't lead to a valid solution. In generating permutations, you try all character arrangements and backtrack when necessary, ensuring that each valid permutation is generated without duplication and in an efficient manner.

9. What are the performance concerns when generating large permutations?

Generating permutations of large datasets can lead to performance issues due to the high time complexity (factorial growth) and high memory consumption, especially when using recursion. Recursive methods can also cause stack overflow for huge input sizes, while iterative methods may require more complex logic to manage memory efficiently.

10. How do I handle edge cases when generating permutations in Java?

To handle edge cases, ensure that your algorithm considers special cases such as empty strings, strings with a single character, and strings where all characters are the same. For empty or single-character strings, return the string itself. For strings with identical characters, avoid generating duplicate permutations by skipping over repeated characters during the permutation process.

11. Can permutation in Java handle duplicate values in input?

Yes, permutation in Java can be adapted to handle duplicates, but it requires extra logic to avoid repeating the same arrangement. Common techniques include using a Set to track generated permutations or sorting the input and skipping over repeated elements during generation. This ensures that your output only contains unique permutations, which is especially useful in problems involving repeated characters or numbers.

Rohan Vats

408 articles published

Rohan Vats is a Senior Engineering Manager with over a decade of experience in building scalable frontend architectures and leading high-performing engineering teams. Holding a B.Tech in Computer Scie...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks

IIIT Bangalore logo
new course

Executive PG Certification

9.5 Months