How to check whether two strings are anagram or not in Java?

In this Java tutorial, we will learn how to check if two strings are anagram or not in Java. Below I have provided an easy example for a better understanding.

Let’s suppose there are two strings example, a and b are known as anagrams if, the frequency of all the characters in a is equal to that of b. For example, the anagrams of MAT are MAT, AMT, TAM, TMA, ATM, and MTA.

How to check if two strings are anagram or not in Java

Input Format

The first line contains a string denoting.

The second line contains a string denoting.

Output Format

Print “They are Anagrams” if a and b are case-insensitive anagrams of each other.

//java8

import java.util.Scanner;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Solution
{
static boolean isAnagram(String A, String B) {
A = A.trim().toLowerCase();
B = B.trim().toLowerCase();
if (A.length() == B.length()) {
int[] a = A.chars().sorted().toArray();
int[] b = B.chars().sorted().toArray();
boolean f = true;
for (int i = 0; i < b.length; i++) {
if (a[i] != b[i]) {
f = false;
break;
}
}
return f;
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
String B = sc.next();
boolean ret = isAnagram(A, B);
if (ret) {
System.out.println("They are Anagrams.");
} else {
System.out.println("They ain't Anagrams.");
}
}
}
A = A.trim().toLowerCase();

toLowerCase() method will convert the string to lowercase. In a similar way, we have converted the string B to lower case. You can make both of them to the upper case too. Just make sure both of the strings are in the same case.

Input 1

missisippi

ssippmiipi

Output 1

They ain't Anagrams.

Explanation:

This does not satisfy the Anagram rule.

Input 2

Better

better

Output 2

They are Anagrams.

Explanation:

This satisfies the Anagram rule. ( As this is case insensitive )

You might also read,

FizzBuzz Problem In Java- A java code to solve FizzBuzz problem

Leave a Reply

Your email address will not be published. Required fields are marked *