Java Program to Check if Two Strings are Anagram - The Coding Shala

Home >> Java Programs >> Check if Two Strings are Anagram

 Hey there, welcome back to another post. In this post, we will learn how to check if two strings are anagram or not in Java.

Java Program to Check if Two Strings are Anagram

Two strings are called anagrams if one string can be converted to another string by rearranging the characters of the first string. For example:

String a = "race" and String b = "care" are anagrams, because from string "race" we can make the string "care".

By using the below ways, we can check if two strings are anagram or not:

  1. Convert strings to char arrays then sort the arrays.

Java Example to Check if Two Strings are Anagram using Sorting

Strings are anagram if the below conditions are true:

  • The length of both strings should be the same.
  • Characters and their frequencies should be the same in both the string.

We can convert both the strings to char array. After sorting the arrays we can check if both the array are the same or not.

Java Program: 

import java.util.Arrays;

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static boolean isAnagram(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }

        // convert to lower case and then char array
        char[] charArr1 = str1.toLowerCase().toCharArray();
        char[] charArr2 = str2.toLowerCase().toCharArray();

        // sort both arrays so we can compare
        Arrays.sort(charArr1);
        Arrays.sort(charArr2);

        // compare and return
        // we can compare using for loop or equals() method
        return Arrays.equals(charArr1, charArr2);
    }

    public static void main(String[] args) {
        String str1 = "Race";
        String str2 = "care";

        if (isAnagram(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagram.");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagram.");
        }
    }
}

Output: 

Race and care are anagram.


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala