To check whether the two string are anagram or not anagram in Java programming, you have to ask to the user to enter the two string to start checking for anagram.
Two string will be anagram to each other if and only if they contain the same number of characters (order of the characters doesn't matter).
That is, If the two strings are anagram to each other, then one string can be rearranged to form the other string.
For Example:
abc and cba are anagram.
creative and reactive are also anagram.
Following Java program illustrates it :
Following is the Java Anagram Program Source code :
/* Java Program Example - Check Anagram or Not */ import java.util.Scanner; public class JavaProgram { public static void main(String[] input) { String str1, str2; int len, len1, len2, i, j, found=0, not_found=0; Scanner scan = new Scanner(System.in); System.out.print("Enter First String : "); str1 = scan.nextLine(); System.out.print("Enter Second String : "); str2 = scan.nextLine(); len1 = str1.length(); len2 = str2.length(); if(len1 == len2) { len = len1; for(i=0; i<len; i++) { found = 0; for(j=0; j<len; j++) { if(str1.charAt(i) == str2.charAt(j)) { found = 1; break; } } if(found == 0) { not_found = 1; break; } } if(not_found == 1) { System.out.print("Strings are not Anagram to Each Other..!!"); } else { System.out.print("Strings are Anagram"); } } else { System.out.print("Both Strings Must have the same number of Character to be an Anagram"); } } }
When the above Java Program is compile and executed, it will produce the following output. Above Java Programming Example Output (Anagram String):
Above Java Programming Example Output (Not Anagram String):
Here fist we have to check the length of both the strings, if the length will be equal then further proceed else print the message for the unequal length.
Now compare the first character of the first string to all the character of the second string one by one, then compare the second character of the first string to all the character of second string one by one, and so on.
When comparing, if any of the character of the first string will match to the character of the second string, then we initialize 1 to the found, and exit the loop and if there will no match found for any character, then 1 will not initialize to the found. So found will be equal to 0, so that after exiting the inner loop, on checking "if(found == 0)", it becomes true and 1 will be initialize to not_found and exit the outer loop. Now after exiting or completing the outer loop, we have to check whether not_found will be equal to 1 or 0. If not_found will be equal to 1, then the string are not anagram and if not_found will be equal to 0 then the strings will be anagram
You may also like to learn and practice the same program in other popular programming languages:
Tools
Calculator
Quick Links