Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 59

Anagram Check Program in Java

In this lesson: Check if two strings are anagrams in Java using sorting and counting — code, dry run and output. In Hindi & English.

What is an anagram

Two words are anagrams if they use exactly the same letters, just in a different order — like listen and silent. Checking for anagrams in Java is a classic string exercise, and there are two neat ways: sorting and counting characters.

💡 Anagrams contain the same letters the same number of times, only rearranged.

The sorting method

import java.util.Arrays;

String a = "listen", b = "silent";
char[] x = a.toCharArray();
char[] y = b.toCharArray();
Arrays.sort(x);
Arrays.sort(y);
System.out.println(Arrays.equals(x, y));
true

We turn each string into a char array, sort both, and compare. If they are anagrams, sorting makes them identical — Arrays.equals then returns true.

Dry run

Dry Run — are "listen" and "silent" anagrams? (sort both)
StepWhatValue
1chars of "listen"l i s t e n
2sortede i l n s t
3chars of "silent"s i l e n t
4sortede i l n s t
5compare sorted arrayse i l n s t == e i l n s t → Anagram!
💡 Understand it this way

Anagrams use the same letters, so once both are sorted they become identical. Comparing the sorted forms is a quick, reliable check.

The counting method

String a = "listen", b = "silent";
if (a.length() != b.length()) {
    System.out.println("Not anagram");
} else {
    int[] count = new int[26];
    for (char c : a.toCharArray()) count[c - 'a']++;
    for (char c : b.toCharArray()) count[c - 'a']--;
    boolean anagram = true;
    for (int n : count) if (n != 0) anagram = false;
    System.out.println(anagram);
}
true

We add up letters from the first word and subtract those from the second. If every count ends at 0, both words used the same letters — they are anagrams. This avoids sorting.

Cleaning the input

For real checks, ignore case and spaces first:

a = a.toLowerCase().replaceAll("\\s", "");
b = b.toLowerCase().replaceAll("\\s", "");

This lets "Listen" and "Silent", or phrase anagrams like "conversation" and "voices rant on", compare correctly regardless of case and spacing.

Common mistakes

  • Not checking lengths. Different lengths can never be anagrams — check first.
  • Ignoring case and spaces. Lowercase and strip spaces for phrases.
  • Comparing arrays with ==. Use Arrays.equals, not ==.
  • Assuming only lowercase letters in counting. The c - 'a' trick assumes a-z only.

Summary

  • Anagrams use the same letters in a different order.
  • Sorting method: sort both char arrays and compare with Arrays.equals.
  • Counting method: add letters from one, subtract from the other, check all zeros.
  • Lowercase and remove spaces for phrase anagrams.
  • Different lengths mean not anagrams.

Next, reverse text in reverse a string, or sort with bubble sort.

Frequently Asked Questions

What is an anagram?
Two words are anagrams if they contain exactly the same letters in a different order. For example "listen" and "silent" are anagrams. Checking involves confirming both words use the same letters the same number of times.
How do I check if two strings are anagrams in Java?
The simplest way is to sort the characters of both strings and compare them — if the sorted forms are equal, they are anagrams. Another way is to count each character in both and compare the counts.
What is the sorting method for anagrams?
Convert each string to a char array, sort both arrays, and compare them. Anagrams become identical once sorted, because they contain the same letters. It is short and easy to understand.
What is the character-count method?
Count how many times each character appears in both strings, then compare the counts. If every character appears the same number of times in both, they are anagrams. This avoids sorting.
Should I ignore case and spaces when checking anagrams?
Often yes. For phrases, convert both to lowercase and remove spaces first, so "Listen" and "Silent" or "conversation" and "voices rant on" compare correctly. For simple words, a direct check is fine.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicRemove Duplicates Your progress: 59 / 61 (97%) · Lesson 60 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free