Check if Two Strings are Permutations

This program checks if two strings are permutations of each other.

Problem Statement

Write a Java program to check if "abc" and "cab" are permutations.

Source Code

1 import java.util.Arrays;
2 public class CheckPermutation {
3 public static void main(String[] args) {
4 System.out.println("Eduinq Check Permutation");
5 String s1="abc", s2="cab";
6 char[] a1=s1.toCharArray(), a2=s2.toCharArray();
7 Arrays.sort(a1); Arrays.sort(a2);
8 if(Arrays.equals(a1,a2)) System.out.println("Strings are permutations");
9 else System.out.println("Strings are not permutations");
10 }
11 }

Program Output

Eduinq Check Permutation
Strings are permutations

Explanation

Both strings are converted into character arrays and sorted, and Arrays.equals() checks if the sorted arrays match exactly, demonstrating a check for permutation equivalence between two strings.

Quick Links to Explore