Java Program to Check Two Strings are Anagram or Not

  • Java program to check two strings are anagrams or not.

In this java program, we have to check whether two strings are anagram or not and print the result on screen. Two strings are anagram of each other, if we can rearrange characters of one string to form another string.

In other words, two strings are anagram, if character frequency of both strings are identical. All the characters of one string should appear same number of time in other string and their should not be any character which is only present in one string but not in other string.

For Example,
"debit card" and "bad credit" are anagram
"mango" and "namgo" are anagram

Java program to check two strings are anagram or not

To check whether two strings are anagram or not, we first ask user to enter two strings and store them in str1 and str2 String objects. Then we convert str1 and str2 to characters arrays and store them in array1 and array2 respectively. We sort the character sequence array1 and array2 and then compare them. If both are equal then input strings are anagram else not anagram.

package com.tcc.java.programs;

import java.util.Arrays;
import java.util.Scanner;

/**
 * Java Program to Reverse a String using loop
 */
public class Anagram {
    public static void main(String args[]) {
        String str1, str2;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter First String");
        str1 = scanner.nextLine();

        System.out.println("Enter Second String");
        str2 = scanner.nextLine();

        char[] array1 = str1.toCharArray();
        char[] array2 = str2.toCharArray();

        Arrays.sort(array1);
        Arrays.sort(array2);

        if (String.valueOf(array1).equals(String.valueOf(array2))) {
            System.out.println("Anagram String");
        } else {
            System.out.println("Not Anagram String");
        }
    }
}
Output
Enter First String
Apple
Enter Second String
ppleA
Anagram String
Enter First String
mother inlaw
Enter Second String
women hitlar
Anagram String
Enter First String
Banana
Enter Second String
PineApple
Not Anagram String