Last Updated on December 27, 2022 by Prepbytes
We will learn how to determine whether two strings are anagrams in this post. A word or phrase created by rearranging the letters of another word is known as an anagram. Two strings are input by the user. Each letter (from ‘a’ to ‘z’) must be counted in order for us to compare the matching numbers. The number of times an alphabet appears in a string is its frequency. We may claim that two strings are anagrams if they both include the same number of instances of a certain alphabet.
What is Anagram in Java?
Anagrams are strings that have the exact same characters in them but are arranged differently.
For example :
- "now" and "own"
- "ton" and "not"
- "fiber" and "brief"
Below is a demonstration of the same −
Input
Suppose our input is −
Enter the first string: Race
Enter the second string: Care
Output
The desired output would be −
The strings race and care are anagrams.
Anagram Program Algorithm:
- START
- Declare two string values namely my_string_1, my_string_2
- Read the required values from the user/ define the values
- Convert both the strings to lowercase letters using the toLowerCase() function
- Check if the length of the two strings is the same, if not, they are not anagram strings.
- Assign the strings to character arrays and sort them.
- Use the function ‘equals()’ to check if they are equal. If yes, they are anagram strings, else they are not anagram strings.
- Display the result
- Stop
Java Anagram Program Code
We can write Anagram program in Java by using the following methods
Method 1: Pseudo Code for Anagram Program in java using sort() and equals() method:
- Remove all white spaces from the two strings and convert them to uppercase.
- Use toCharArray() to turn the two strings into char arrays.
- Sort the two character arrays using sort() method of java.util.Arrays class.
- Using the equals() function, we compare the two arrays after sorting.
Code Implementation:
import java.util.*; import java.io.*; class Anagram { public static void main (String[] args) throws java.lang.Exception { boolean result = isAnagram("now","own"); System.out.println(result); } public static boolean isAnagram(String first, String second) { // remove all whitespaces and convert strings to lowercase first = first.replaceAll("\\s", "").toLowerCase(); second = second.replaceAll("\\s", "").toLowerCase(); /* check whether string lengths are equal or not, if unequal then not anagram */ if (first.length() != second.length()) return false; // convert string to char array char[] firstArray = first.toCharArray(); char[] secondArray = second.toCharArray(); // sort both the arrays Arrays.sort(firstArray); Arrays.sort(secondArray); // checking whether both strings are equal or not return Arrays.equals(firstArray,secondArray); } }
Output: true
Method 2: Pseudo Code for Anagram Program in java using Iterative method:
- The next step in this procedure is to verify that every character from the first string is present in the second string.
- If the character is also present in the second string, it is removed, and the first string character is then moved on to.
- If any character from the first string is missing from the second string, the loop is broken, and the conclusion is that the first string and the second string are not anagrams.
Code Implementation:
import java.util.*; import java.lang.*; import java.io.*; class Anagram { public static void main (String[] args) throws java.lang.Exception { boolean result = isAnagram("now","own"); System.out.println(result); } public static boolean isAnagram(String first, String second) { // remove all whitespaces and convert strings to lowercase first = first.replaceAll("\\s", "").toLowerCase(); second = second.replaceAll("\\s", "").toLowerCase(); /* check whether string lengths are equal or not, if unequal then not anagram */ if (first.length() != second.length()) return false; // convert first string to char array char[] firstArray = first.toCharArray(); // check whether each character of firstArray is present in second string for (char c : firstArray) { int index = second.indexOf(c); // indexOf function returns -1 if the character is not found if (index == -1) return false; // if character is present in second string, remove that character from second string second = second.substring(0,index) + second.substring(index+1, second.length()); } return true; } }
Output: true
Method 3: Pseudo Code for Anagram Program in java using HashMap method:
- HashMap object should be created with a character as the key and character occurrences as the value.
- We increase the character count by 1 if the character is present in the first string.
- We reduce the character count by 1 if the character is present in the second string.
- Check the count of each character in the hashmap as you iterate over it, and if the count is not equal to 0, return false.
Code Implementation:
import java.util.*; import java.io.*; class Anagram { public static void main (String[] args) throws java.lang.Exception { isAnagram("now","own"); } public static void isAnagram(String stringOne, String stringTwo) { //Remove all white space & case differences String strCopyOne = stringOne.replaceAll("\\s", "").toUpperCase(); String strCopyTwo = stringTwo.replaceAll("\\s", "").toUpperCase(); //If the strings aren’t the same length, not anagrams if (strCopyOne.length() != strCopyTwo.length()) { System.out.println(stringOne + " and " + stringTwo + " are not anagrams."); return; } //HashMap to store the number of characters HashMap mapOne = createMapKeys(strCopyOne); HashMap mapTwo = createMapKeys(strCopyTwo); if (mapOne.equals(mapTwo)) { System.out.println(stringOne + " and " + stringTwo + " are anagrams"); } else { System.out.println(stringOne + " and " + stringTwo + " are not anagrams."); } } public static HashMap createMapKeys(String str) { HashMap map = new HashMap(); for (int i = 0; i < str.length(); i++) { if (map.containsKey(str.charAt(i))) { int count = (int) map.get(str.charAt(i)); map.put(str.charAt(i), count + 1); } else { map.put(str.charAt(i), 0); } } return map; } }
Output: now and own are anagrams
I Hope this article will help in understanding anagram program in java. Practice more questions like anagram if you are a beginner, as it will increase your logic building as well as the implementation part.
Other Java Programs
Java Program to Add Two Numbers
Java Program to Check Prime Number
Java Program to Check Whether a Number is a Palindrome or Not
Java Program to Find the Factorial of a Number
Java Program to Reverse a Number
Java Program to search an element in a Linked List
Program to convert ArrayList to LinkedList in Java
Java Program to Reverse a linked list
Java Program to search an element in a Linked List