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
- Sort both strings and compare
- Or count character frequencies
- Must have same length first
Related Strings exercises
- Practice Count Words in Java
- Practice First Non-Repeating Character in Java
- Practice Longest Word in Java
Practice all Strings exercises · Run this idea in the Java compiler