A simple program to check anagrams in java


This is a simple program in Java. This program can be used to check if the two given strings are anagram. Two given strings are said to be anagrams when they have equal length and same characters are present in both the Strings. An example of anagram strings is SILENT and LISTEN!


import java.util.*;

public class Anagram {
  public static boolean isAnagram(String s1, String s2) {
    if (s1.length() != s2.length()) {
      return false;
    s1 = sortCharacters(s1);

    s2 = sortCharacters(s2);
    return s1.equals(s2);

  public static String sortCharacters(String str) {
    char[] c = str.toLowerCase().toCharArray();
    return String.valueOf(c);
  public static void main(String arg[]) {
    String s1, s2;
    Scanner sc = new Scanner(System.in);
    System.out.println("enter 2 strings");
    s1 = sc.nextLine();
    s2 = sc.nextLine();
    if (isAnagram(s1, s2))
      System.out.println(s1 + "is an anagram" + s2);
      System.out.println(s1 + "is not an anagram" + s2);


Got anything to say, please do comment here.

Related posts

Leave a Comment