program to check anagram in java

In this post we will write a program to check anagram in java. a word is called an anagram, if they contains the same characters but in different order. An example of anagram is listen and silent, both string contains the same characters but in different order. there are different logic to check anagram out of which we will see some common logic’s in below examples.

Program to check anagram in java:-

import java.util.Arrays;

public class CheckAnagram {

	static boolean isAnagramLogic1(String word1, String word2)
	{

		if(word1 == null || word2 == null || word1.length() != word2.length())
		{
			return false;
		}
		char[] array1 = word1.toLowerCase().toCharArray();

		char[] array2 = word2.toLowerCase().toCharArray();

		Arrays.sort(array1);

		Arrays.sort(array2);

		return Arrays.equals(array1, array2);
	}

	static boolean isAnagramLogic2(String word1, String word2) {

		if (word1 == null || word2 == null || word1.length() != word2.length()) {
			return false;
		}

		char[] word1Chars = word1.toLowerCase().toCharArray();
		StringBuilder builder = new StringBuilder(word2.toLowerCase());

		for (Character ch : word1Chars) {
			int index = builder.indexOf(String.valueOf(ch));
			if (index == -1) {
				return false;
			}
			builder.delete(index, index + 1);
		}
		return true;
	}

	static boolean isAnagramLogic3(String word1, String word2){

		if (word1 == null || word2 == null || word1.length() != word2.length()) 
		{
			return false;
		}

		char[] word1Array = word1.toCharArray();

		for (char c : word1Array){
			int index = word2.indexOf(c);

			if(index != -1)
			{
				word2 = word2.substring(0, index)+word2.substring(index+1, word2.length());
			}
			else
			{
				return false;
			}
		}
		return true;
	}

	public static void main(String[] args){

		System.out.println("program to check anagram in java");

		boolean status = false;

		status = isAnagramLogic1("listen", "silent");
		System.out.println(status);

		status = isAnagramLogic1("listen", "silent");
		System.out.println(status);

		status = isAnagramLogic1("listen", "silent");
		System.out.println(status);

		status = isAnagramLogic1("fill", "fire");
		System.out.println(status);

		status = isAnagramLogic1("fill", "fire");
		System.out.println(status);

		status = isAnagramLogic1("fill", "fire");
		System.out.println(status);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *