Java Program to Check if The Given Strings Are Anagram or Not

In this post we’ll see a Java program to check if the given strings are anagram or not.

Two strings are called anagrams if you can get the second string by rearranging all of the  letters in the other string.

As example – Keep and Peek, Dormitory and Dirty room, Listen and Silent

Java program to check if the given strings are anagram or not can be written using the following logic-

  1. By sorting the strings– If you sort both the strings after removing any spaces. Then both the strings should be equal.
  2. By iterating– You can iterate one of the string and search for each character in another string, if each character is found once in the second string then the strings are anagram.

Java program to check for anagrams using sort logic

Output

Java program to check for anagrams using iteration logic

You can use iteration logic to check if the given strings are anagrams or not. For that you need to iterate one of the string char by char and search for the same char in the second string. Each character of the first string should be there in the second string.
Ensure that, if found, character is also deleted from the second string. Not doing that will result in matching the same character again if first string has any character occurring more than once.

Output

That’s all for the topic Java Program to Check if The Given Strings Are Anagram or Not. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.