Problem:- Write a Java program to check whether the given two strings are anagrams or not?
Solution:- So, Let's first understand what is anagrams.
If a string character is equal to the other string characters where the order is not mandatory then that string is anagrams.
for example:- earth and heart, listen and silent, triangle and integral etc.
Here earth and heart have the same characters { 'a', 'e', 'h', 'r', 't' }. So earth and heart are anagram strings.
Java code:-
package com.codeforsolution.java.logical;
import java.util.Arrays;import java.util.Scanner;
public class AnagramsCheck {
public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter 1st String: "); String str1 = input.nextLine(); System.out.println("Enter 2nd String: "); String str2 = input.nextLine(); if (str1.length() == str2.length()) { // earth and heart char[] charArr1 = str1.toCharArray(); // {'e', 'a', 'r', 't', 'h' } char[] charArr2 = str2.toCharArray(); // {'h', 'e', 'a', 'r' ,'t' }
// now sorting char array Arrays.sort(charArr1); // {'a', 'e', 'h', 'r', 't' } Arrays.sort(charArr2); // {'a', 'e', 'h', 'r', 't' }
boolean returnValue = Arrays.equals(charArr1, charArr2); if (returnValue) { System.out.println("String " + str1 + " and " + str2 + " is anagram"); } else { System.out.println("String " + str1 + " and " + str2 + " is not anagram"); }
} else { System.out.println("String " + str1 + " and " + str2 + " is not anagram"); } input.close();
}
}
Output:-
Enter 1st String:
triangle
Enter 2nd String:
integral
String triangle and integral are anagrams.
Here is the link to a YouTube video for the same program:- Anagram check