Java Online Compiler
Example: Anagram Checker (Sorting) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Anagram Checker (Sorting) import java.util.Arrays; // Required for Arrays.sort() and Arrays.equals() import java.util.Scanner; // Main class containing the entry point of the program public class Main { /** * Checks if two strings are anagrams by sorting their characters. * Ignores case and non-alphabetic characters. * * @param str1 The first string. * @param str2 The second string. * @return true if the strings are anagrams, false otherwise. */ public static boolean areAnagramsUsingSort(String str1, String str2) { // Step 1: Handle null or empty strings if (str1 == null || str2 == null) { return false; } if (str1.isEmpty() && str2.isEmpty()) { return true; } // Step 2: Normalize strings (remove spaces, convert to lowercase) // This makes the comparison case-insensitive and ignores spaces. String processedStr1 = str1.replaceAll("\\s", "").toLowerCase(); String processedStr2 = str2.replaceAll("\\s", "").toLowerCase(); // Step 3: Check if lengths are different after processing if (processedStr1.length() != processedStr2.length()) { return false; } // Step 4: Convert strings to character arrays char[] charArray1 = processedStr1.toCharArray(); char[] charArray2 = processedStr2.toCharArray(); // Step 5: Sort both character arrays Arrays.sort(charArray1); Arrays.sort(charArray2); // Step 6: Compare the sorted character arrays // Arrays.equals() efficiently compares the contents of two arrays return Arrays.equals(charArray1, charArray2); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("--- Anagram Checker (Sorting Method) ---"); System.out.print("Enter first string: "); String s1 = scanner.nextLine(); System.out.print("Enter second string: "); String s2 = scanner.nextLine(); boolean isAnagram = areAnagramsUsingSort(s1, s2); if (isAnagram) { System.out.println("\"" + s1 + "\" and \"" + s2 + "\" are anagrams."); } else { System.out.println("\"" + s1 + "\" and \"" + s2 + "\" are NOT anagrams."); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS