# Anagram Program in Java : Check whether Two Strings are Anagrams of each other

Write a anagram program in java or Java program to check anagram. In this programming question, we are going to write a java code to check whether two strings are anagrams of each other.

Let’s first understand what is an anagram? and how we are going to solve this problem.

## What is an Anagram?

Two strings are said to be anagrams of each other if it contains the same characters, only the order of characters in both the strings is different. In other words, both strings must contain the same exact letters in the same exact frequency.

Let’s understand it through an example –

For example –

i)

str1 – car

str2 – rac

In this example, str1 and str2 are anagrams of each other. As both the strings contain the same letters only the order of characters in both the strings is different.

ii)

str1 – code

str2 – dock

In this example, str1 and str2 are not an anagram of each other. As both, the strings contain different letters.

Now we know what’s an Anagram . Let’s think for a moment how do we write a code to check whether two strings are anagrams of each other. In this tutorial, i am going to discuss two approaches to solve this problem.

Programming questions for practice

Subscribe Our Tutorials

Anagram Program in Java

## How to Check whether Two Strings are Anagrams of each other

Method  1 – Use Sorting

The easiest approach is to sort both the strings and after sorting compare them. If sorted strings is equal then it’s an anagram otherwise it’s not.

The time complexity of this approach is O(nlogn).

Sorting algorithms and their time complexity

## Java Program to Check Anagram using Sorting

METHOD 2- Check if both Strings have the same count for each character

In this method, we count each character of the first string then subtracting it from the count of the second string. Finally, check if the character count is zero. It it is not zero(0) then the two string is not an anagram.

The time complexity of this approach is O(n).