What is Anagram?

Two Strings are said to be anagrams, only if all the characters present in first string and second string are equal. Anagrams words or numbers must have same length. But, characters are rearranged (it allows special characters also). Words can be in Upper or Lower case.

Anagram example

  • consider two strings state and taste.
  • Both the strings have same length.
  • Both strings have same letters and rearranged in two different words.

some more examples of Anagrams are

arc and car

elbow and below

Java code to check if two Strings are Anagrams are not :

import java.util.Arrays;
import java.util.Scanner;
class Programming9
{
	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in); 
		System.out.println("Enter the two Strings:");
		String s=sc.nextLine();
		String s1=sc.nextLine();
		s=s.replaceAll(",","");// it eliminates spaces between strings
		s1=s1.replaceAll(",","");

		if(s.length()==s1.length()) // to check if the string length is equal or not
		{
			// toLowerCase()-Words should be printed in lower case.
			// toCharArray()-Strings to char array
			char ch[]=s.toLowerCase().toCharArray();
			char ch1[]=s1.toLowerCase().toCharArray();
			Arrays.sort(ch);//sort the elements in the ascending order
			Arrays.sort(ch1);
			if(Arrays.equals(ch,ch1)) // equals method checks condition character by character
			{
				System.out.println("Anagrams");
			}
			else
			{
				System.out.println("Not Anagrams");
			}

		}
		else {
			System.out.println("Not Anagrams");
		}
	}
}
Enter the two Strings:
programing9
9pRograming
Anagrams
Enter the two Strings:
elbow
BeLoW
Anagrams