LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Predict the Output · Question 19

Checking anagrams by sorting characters Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Arrays;

public class Main {
    static boolean anagram(String a, String b) {
        char[] x = a.replace(" ", "").toLowerCase().toCharArray();
        char[] y = b.replace(" ", "").toLowerCase().toCharArray();
        Arrays.sort(x);
        Arrays.sort(y);
        return Arrays.equals(x, y);
    }

    public static void main(String[] args) {
        System.out.println(anagram("Listen", "Silent") + " " + anagram("Dormitory", "Dirty room") + " " + anagram("Java", "Jaav") + " " + anagram("Hello", "World"));
    }
}
  • A true true true false Correct
  • B true false true false
  • C false true true false
  • D true true false false
Correct Answer: Option A

Two strings are anagrams when their sorted letters are equal (after removing spaces and ignoring case).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links