check if two String are Anagram

Java Program to check if two String are Anagram

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase.

For example:

Two strings str 1 = arc and str2 = car is anagram because it has same alphabets with same time of repetition.

Java concept used here are

  • str1.toCharArray() – This will converts the string into a char array
  • Arrays.sort() – sort() method of array sorts the char arrays
  • Arrays.equal() – It will check two sorted arrays are equal

Below is the Java program that checks if two strings are anagrams

import java.util.Arrays;
import java.util.*;
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Please give First String : ");
    String str1 = sc.nextLine();
    Scanner sc1 = new Scanner(System.in);
    System.out.print("Please give Second String : ");
    String str2 = sc.nextLine();
    if (str1.length() != str2.length()) {
      System.out.println("The strings are not anagrams.");
      return;
    }
    //convert string to char arrays
    char[] charArray1 = str1.toCharArray();
    char[] charArray2 = str2.toCharArray();

    // sort the char arrays
    Arrays.sort(charArray1);
    Arrays.sort(charArray2);

    // check if the sorted char arrays are equal
    if (Arrays.equals(charArray1, charArray2)) {
      System.out.println("The strings are anagrams.");
    } else {
      System.out.println("The strings are not anagrams.");
    }
  }
}

Output

Please give First String : car
Please give Second String : arc
The strings are anagrams.