Anagram program in Java


Simple Anagram program in Java

What is Anagram?

An anagram is a word or a phrase, which is formed by rearranging the letters or characters of another word or phrase.

Examples of Anagram:

expect - except
insect - nicest
rescued - reduced
thicken - kitchen
drawback - backward
Below is a simple Java code for Checking if two strings are Anagrams or not

Java Program to check if Two Strings are Anagram:

import java.util.Arrays; import java.util.Scanner; public class Anagram{ static void isStringAnagram(String first, String second) { // Remove all space from both Strings String s1 = first.replaceAll("\\s", ""); String s2 = second.replaceAll("\\s", ""); boolean status = true; if (s1.length() != s2.length()) { status = false; } else { char[] S1Array = s1.toLowerCase().toCharArray(); char[] S2Array = s2.toLowerCase().toCharArray(); Arrays.sort(S1Array); Arrays.sort(S2Array); status = Arrays.equals(S1Array, S2Array); } if (status) { System.out.println(s1 + " and " + s2 + " are anagrams"); } else { System.out.println(s1 + " and " + s2 + " are not anagrams"); } } public static void main(String[] args) { Scanner sc =new Scanner(; System.out.println("Enter first word or phrase"); String first=sc.nextLine(); System.out.println("Enter second word or phrase"); String second=sc.nextLine(); isStringAnagram(first,second); } }


C:\Users\Solutionfactory\Desktop\javaPrograms>javac C:\Users\Solutionfactory\Desktop\javaPrograms>java Anagram Enter first word or phrase drawback Enter second word or phrase backward drawback and backward are anagrams C:\Users\Solutionfactory\Desktop\javaPrograms>java Anagram Enter first word or phrase A gentleman Enter second word or phrase Elegant man Agentleman and Elegantman are anagrams C:\Users\Solutionfactory\Desktop\javaPrograms>

Solution Worked 0 UpvotesUpvote


Solution Didn't Worked 0 DownvotesDownvote


Get Programming Help

Play 2048 Game Online

Search Tags

    Java code for anagram

    Anagrams in Java