How to check two strings are anagram or not in java

check strings are anagram or not

How to check strings are anagram or not in java

What is String Anagram and how to check strings are anagram or not ? This type of program is  may chance to ask in java interview or in practical exam.So we have to know the solution for this kind of problem. Sometimes solution is so easy but we don’t know the meaning of that think at that time could not solve it. So first of all we have to know the proper meaning of it and then it’s solution.

So first of all we have to know the proper meaning of a String Anagram.

String Anagram :

An anagram is word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Ex.  LISTEN

If we rearrange the letters of LISTEN then we can get SILENT. So LISTEN and SILENT are anagrams.

Solution:

Now,How to check strings are anagram or not in java

So here is the solution….

  • First of all we have to take two string and sort them in alphabetic order. After sorting if both String are same then both are Anagrams otherwise not.

Also Read: Java program to count number of vowels in a sentence

Also Read: Swap two variables without using Third Variable in Java

Program:

import java.util.Arrays;

public class StringAnagramOrNot {

    public static void main(String[] args) {

        String str1 = "LISTEN";
        String str2 = "SILENT";

        System.out.println("String is Anagram ? : " + anagram(str1, str2));

    }

    public static boolean anagram(String s1, String s2) {
        char[] ch1 = s1.toCharArray();
        char[] ch2 = s2.toCharArray();

        Arrays.sort(ch1);
        Arrays.sort(ch2);

        return Arrays.equals(ch1, ch2);
    }

}

Download a program to check strings are anagram or not, click here.

Output:

check strings are anagram or not

Note : In this program we have to import Arrays class because sort method is available in this class and this we need to sort Character array in Ascending order.


So I hope use got what is String Anagram and ‘How to check two strings are anagram or not in java’.

Thank you 🙂

Stay Connected with Place4Java and Follow us our Facebook Page.

2 Trackbacks / Pingbacks

  1. String is Palindrome or Not in Java program Explained !!
  2. Print serial number without use of any kind of Loop or Print Statement

Leave a Reply

Your email address will not be published.


*