Java program to check if two strings are Anagram or not

Check two strings are anagram or not

Anagram words are words which are created by rearranging the letter of a single word to form various different words with different meanings. This is a good way for increasing one vocabulary in english. Anagrams words have the same word length, but the characters are rearranged, here we have coded a java program to find out whether two words are anagram or not
Lets take an example
  • Consider two strings elbow and below
  • Both the strings have the same length
  • Both the strings have same letters
  • But the letters are re-arranged in a way to form two different words
some more examples of anagram words are arc and car, state and taste, night and thing and  many more


Check if two strings are Anagram or not


  • Take string input from user and store it in the variable called “str” .
  • Call isAnagram() method by passing two string as parameter .
  • Write if condition if(s1.length()!=s2.length()) set statue = false;
  • else  convert both array to character arrya using toCharArray()
  • After that sort both the array using Arrays class sort() after that return status

Code in Java

import java.util.Arrays;
import java.util.Scanner;
public class CheckIfTwoStringsAreAnagramAreNot {
    static boolean isAnagram(String str1 , String str2) {
    String s1 = str1.replaceAll("[\\s]", "");
    String s2 = str2.replaceAll("[\\s]", "");
    boolean status=true;

         status = false;
     else {
         char[] a1 = s1.toLowerCase().toCharArray();
         char[] a2 = s2.toLowerCase().toCharArray();
         status = Arrays.equals(a1, a2);
       return status;
   public static void main(String[] args) {
     Scanner sc = new Scanner(;
     System.out.print("Enter two String :");
     String s1 =;
     String s2 =;
     boolean status = isAnagram(s1,s2);
          System.out.println(s1+" and "+s2+" are Anagram");
          System.out.println(s1+" and "+s2+" are not Anagram");
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)


Enter two String : prep
prep and repp are Anagram