Anagram Check in Java: Explanation & Practice

Check if two strings are anagrams

Problem summary

Write a program that checks if two strings are anagrams (same characters, different order).

Starter code

public class Main {
    public static void main(String[] args) {
        String s1 = "listen";
        String s2 = "silent"; // Test case 1
        
        // Check if anagrams
        // Print: Are anagrams: <true/false>
    }
}

Expected output and test cases

  • listen/silent are anagrams
    Are anagrams: true
  • triangle/integral
    Are anagrams: true
  • hello/world not anagrams
    Are anagrams: false

Hints

  1. Sort both strings and compare
  2. Or count character frequencies
  3. Must have same length first

Related Strings exercises

Practice all Strings exercises · Run this idea in the Java compiler