Java program to check if two strings are Anagram or not

Share

The Java program checks if two given strings are anagram or not. It can be done in two ways, first is by comparing each character of a string, and the second way is by sort the given strings and then compare it.

What is an Anagram String?

When two strings are having exactly the same number of characters where each and every character in both strings are identical without considering the order.

For example, rail and liar are two anagrams, as both have the same number of characters, only the fact is that the letters are rearranged to form meaningful words.

Java program to check if two Strings are Anagram or not by Comparing each character

Program:

/**
Check if two Strings are anagrams by Comparing each character
**/
public class StringAnagram {

public static void main(String[] args) {
String first = "Programmerbay";
String second= "bayprogrammer";
char[] ch1 = first.toLowerCase().toCharArray();
char[] ch2 = second.toLowerCase().toCharArray();
int i,j,count1,count2;
int firstLen = ch1.length;
int secondLen = ch2.length;

if(firstLen==secondLen)
{
count1=0;
count2=0; 
for(i=0;i<firstLen;i++)
{
count1++;
for(j=0;j<firstLen;j++)
{
if(ch1[i]==ch2[j]) 
{
count2++;
break;
}

}
}
}else{
count1=0;
count2=1;
}
if(count1==count2)
System.out.println(first+" and "+second+ " are Anagrams");
else
System.out.println(first+" and "+second+ " are't Anagrams");
}

}

Output:

Programmerbay and bayprogrammer are Anagrams

Java program to check if two Strings are Anagram or not by using the Sort method

Program:

/**
Check if two Strings are anagrams by using the Sort method
**/
import java.util.Arrays;

public class StringAnagram {

    public static void main(String[] args) {
        String first = "Programmerbay";
        String second = "bayprogrammer";
        char[] firstArr = first.toLowerCase().toCharArray();
        char[] secondArr = second.toLowerCase().toCharArray();
        Arrays.sort(firstArr);
        Arrays.sort(secondArr);
        if (String.valueOf(firstArr).equals(String.valueOf(secondArr))) {
            System.out.println("They are anagrams!");
        } else {
            System.out.println("They are not anagrams!");

        }

    }

}

Output: 

They are anagrams!

This post was last modified on December 6, 2020

Sandeep Verma

Published by
Sandeep Verma
Tags: anagram check if two strings are anagrams java check whether two strings are an anagram or not java java program Java program to check whether two strings are an anagram or not numbers program