Programming Examples

Java program to check whether the two strings anagram of each other or not

Anagram :- When two strings contain the same characters irrespective of the order of occurrence then such strings are known as Anagram.

For Example :-

String1 = LISTEN

String2 = SILENT

So as we can see that both strings have same characters, only the order of characters is different so this is an Anagram.


import java.util.Arrays; 
import java.util.Collections; 
class LFC { 
static boolean anagram(char[] str1, char[] str2) 
// Get lenghts of both strings 
int len1 = str1.length; 
int len2 = str2.length; 
// If length of both strings is not same, 
// then they cannot be anagram 
if (len1 != len2) 
return false; 
// Sort both strings 
// Compare sorted strings 
for (int i = 0; i < len1; i++) 
if (str1[i] != str2[i]) 
return false; 
return true; 
/* Driver program to test to print printDups*/
public static void main(String args[]) 
char str1[] = { 'l', 'i', 's', 't', 'e', 'n' }; 
char str2[] = { 's', 'i', 'l', 'e', 'n', 't' }; 
if (anagram(str1, str2)) 
System.out.println("The two strings are"
+ " anagram of each other"); 
System.out.println("The two strings are not"
+ " anagram of each other"); 

The two strings are anagram of each other

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad