Frequently Asked Java Programs: 34 – Java Program to Check if Two Strings are Anagram

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to check if two given strings are anagram.

What are Anagrams strings?

Two words are called Anagrams if they have the same characters with same number of occurance.

For example:- SILENT and LISTEN are anagrams.

We can also say an anagram is a word which can be formed by rearranging all characters of another word in same count.

Problem statement:-

Write a Java program to find two given case insensitive strings are anagram or not .

Solution:-

In fact there are many ways to do above program. Some logics are:-

  1. Sort both strings and check for equal. It is more optimal.
  2. Count occurence of each char in both strings and compare. Continue if counts are same else break.
  3. Iterate char by char and delete/replace character and get length. Break as soon as lengths are different.

But in interview, you are asked to write without using any direct readymade methods. So I will explain two ways here.

Approach 1: – Sort and check equal

As per definition of Anagram above, you can conclude now that two strings should be of equal size and equal sorting order to be anagram.

Logic:-

  1. Compare the length of both strings. If same then go for step 2 otherwise exit as there is no chances to be anagram strings.
  2. Convert both given string to same case.
  3. Sort both strings.
  4. Check equality of both strings. If same, both strings will be anagrams.
package StringPrograms;

import java.util.Arrays;
import java.util.Scanner;

public class AnagramUsingSorting {
	
	
	// Sorting using Stream
	public static boolean areAnagramsUsingStream(String first, String second)
	{
		// Length must be same. Return false if not.
		if(first.length() != second.length())
			return false;
		
		// Converting both strings in to same case
		first= first.toLowerCase();
		second= second.toLowerCase();
		
		
		// Java 8 stream
		// char stream , Sorting and appending
		first= first.chars().sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
		second= second.chars().sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
		
		
		// Checking if both are equals
		if(!(first.equals(second)))
				return false;		
		
		// If all exit criteria are crossed, strings are anagrams
		return true;
		
	}
	
	// Sorting using Arrays
	public static boolean areAnagramsUsingArrays(String first, String second)
	{
		// Length must be same. Return false if not.
		if(first.length() != second.length())
			return false;
		
		// Converting both strings in to same case
		first= first.toLowerCase();
		second= second.toLowerCase();
		
		// COnverting to char array
		char firstArray[]= first.toCharArray();
		char secondArray[]= second.toCharArray();
		
		// Sorting array
		Arrays.sort(firstArray);
		Arrays.sort(secondArray);
		
		// Checking if both are equals
		if(!(Arrays.equals(firstArray, secondArray)))
				return false;		
		
		// If all exit criteria are crossed, strings are anagrams
		return true;
		
	}

	public static void main(String[] args) {
		
		
		Scanner sc = new Scanner(System.in);
		System.out.println("You are going to check anagram strings:- ");
		System.out.println("Enter first string:- ");
		String s1= sc.nextLine();
		System.out.println("Enter second string:- ");
		String s2= sc.nextLine();
		System.out.println(areAnagramsUsingStream(s1, s2) ? s1 +" and "+s2 +" are Anagrams. " : s1 +" and "+s2 +" are not Anagrams. ");
		System.out.println(areAnagramsUsingArrays(s1, s2) ? s1 +" and "+s2 +" are Anagrams. " : s1 +" and "+s2 +" are not Anagrams. ");
		
	}
}

Output:-

You are going to check anagram strings:- 
Enter first string:- Silent
Enter second string:- LIsten
Silent and LIsten are Anagrams. 
Silent and LIsten are Anagrams.
You are going to check anagram strings:- 
Enter first string:- Noon
Enter second string:- Moon
Noon and Moon are not Anagrams. 
Noon and Moon are not Anagrams.

Approach 2: – Iteration

Logic:-

  1. Compare the length of both strings. If same then go for step 2 otherwise exit as there is no chances to be anagram strings.
  2. Iterate any one string char by char.
  3. Check presence of char in another string. If not present exit else go to step 4.
  4. Remove all occurance of checked char from both strings.
package StringPrograms;

import java.util.Scanner;

public class AnagramUsingIteration {
	
	
	
	public static boolean areAnagramsUsingIteration(String first, String second)
	{
		// Length must be same. Return false if not.
		if(first.length() != second.length())
			return false;
		
		// Converting both strings in to same case
		first= first.toLowerCase();
		second= second.toLowerCase();
		
		// Iterate first string
		for(int i =0 ; i



Output:-

You are going to check anagram strings:- 
Enter first string:- Silent
Enter second string:- Listen
Silent and Listen are Anagrams. 
You are going to check anagram strings:- 
Enter first string:- Apple
Enter second string:- Aple
Apple and Aple are not Anagrams. 

#HappyCoding

Leave a Reply

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