How to check whether 2 strings are Anagrams in Java ?

In this article, we will discuss and execute simple program to check whether 2 Strings are Anagrams or not

Anagrams:

  • Anagrams means 2 different strings in different order but contains same characters
  • Arrangement of 2 different strings which contains same characters in different order

 

Anagrams program:

Steps:

  1. First, remove spaces in both strings
  2. set flag for Anagrams
  3. check length of both strings
  4. 3.a if length are not equal, then set flag to false
  5. convert both String to char[]
  6. sort both char[]
  7. check Arrays for equality, after sorting
  8. Finally, print to console
  9. Note : use https://ingesanagram.appspot.com/ for generating difference sequence of Anagram strings

AnagramsProgram.java

package in.bench.resources.anagrams;

import java.util.Arrays;

public class AnagramsProgram {

	public static void main(String[] args) {

		// invoke checkAnagrams
		// https://ingesanagram.appspot.com/
		checkAnagrams("Silent", "Listen");
		checkAnagrams("School Master", "The Classroom");
		checkAnagrams("School Master", "The Classroom");
		checkAnagrams("Fiber", "Brief");
		checkAnagrams("Peek", "Keep");
	}

	public static void checkAnagrams(String str1, String str2) {

		// 1. remove spaces in both strings
		String string1 = str1.replaceAll("\\s", "");
		String string2 = str2.replaceAll("\\s", "");

		// 2. set flag for Anagrams
		boolean anagramsFlag = true;

		// 3. check length of both strings
		if(string1.length() != string2.length()) {
			// 3.a if length are not equal, then set flag to false
			anagramsFlag = false;
		}
		else {
			// 4. convert both String to char[]
			char[] charArray1 = string1.toLowerCase().toCharArray();
			char[] charArray2 = string2.toLowerCase().toCharArray();

			// 5. sort both char[]
			Arrays.sort(charArray1);
			Arrays.sort(charArray2);

			// 6. check Arrays for equality, after sorting
			anagramsFlag = Arrays.equals(charArray1, charArray2);  
		}

		// 7. print to console
		if(anagramsFlag) {
			System.out.println("Both " + string1 + " and " 
					+ string2 + " are Anagrams");
		}
		else {
			System.out.println(string1 + " and " 
					+ string2 + " are NOT Anagrams");
		}
	}
}

Output:

Both Silent and Listen are Anagrams
Both SchoolMaster and TheClassroom are Anagrams
Both SchoolMaster and TheClassroom are Anagrams
Both Fiber and Brief are Anagrams
Both Peek and Keep are Anagrams

Note : There are various other ways to check whether 2 Strings are Anagrams or not

 

Happy Coding !!
Happy Learning !!

Java - How to uppercase every duplicate character in String ?