Anagram Program in Java ISC Computer Science 2025 Practical

Write a program to check if a given string is an Anagram of another string. Two strings are anagrams if they can be rearranged to form the same thing. For example, “listen” and “silent” are anagrams.

Accept two strings from the user and check if they are anagrams of each other. Ensure that the comparison is case-sensitive and ignores spaces. Display an appropriate message based on whether they are anagrams or not. If any of the strings contain invalid characters (e.g., numbers or special characters), generate an error message.

Test your program with the following data and some random data:

Example 1
INPUT:
Enter first string: Listen
Enter second string: Silent
OUTPUT: STRINGS ARE ANAGRAMS

Example 2
INPUT:
Enter first string: Dormitory
Enter second string: Dirty room
OUTPUT: STRINGS ARE ANAGRAMS

Example 3
INPUT:
Enter first string: Hello
Enter second string: World
OUTPUT: STRINGS ARE NOT ANAGRAMS

Example 4
INPUT:
Enter first string: Test123
Enter second string: 321tset
OUTPUT: INVALID CHARACTERS IN STRING. INVALID INPUT

import java.util.Scanner;
class Anagrams{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter first string: ");
        String a = in.nextLine().toUpperCase();
        System.out.print("Enter second string: ");
        String b = in.nextLine().toUpperCase();
        if(!valid(a) || !valid(b)){
            System.out.println("INVALID CHARACTERS IN STRING. INVALID INPUT");
            return;
        }
        a = removeSpaces(a);
        b = removeSpaces(b);
        boolean status = true;
        while(a.length() > 0){
            String x = String.valueOf(a.charAt(0));
            a = a.replace(x, "");
            b = b.replace(x, "");
            if(a.length() != b.length()){
                status = false;
                break;
            }
        }
        if(status)
            System.out.println("THEY ARE ANAGRAMS!");
        else
            System.out.println("THEY ARE NOT ANAGRAMS.");
    }
    public static boolean valid(String s){
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(!Character.isWhitespace(ch) && !Character.isLetter(ch))
                return false;
        }
        return true;
    }
    public static String removeSpaces(String s){
        String str = new String();
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(Character.isWhitespace(ch))
                continue;
            str += ch;
        }
        return str;
    }
}