Online Tutorials & Training Materials | STechies.com
Register Login

Anagram Java Program Example

|| 0

Anagram Java Program Example
Stechies

What is an Anagram?

Two sets of a string are said to be anagram if they contain exactly the same characters but in a different order.

for example: 

Silent and Listen are anagram of each other because both have the same set of characters but in but in different order.

Some Other Anagram Example

The eyes They see
Funeral Real fun
A gentleman Elegant man

In this tutorial, you will learn how to write a Java program to check whether a set of the string are anagram or not.

//Java program to find two strings are anagram or not

//Importing util library with all package
import java.util.*;

//Main / Drived Class
public class Main{

  //main function of the program
  public static void main (String[] args) {
    //Creating object of Scanner Class
    Scanner input = new Scanner(System.in);
    //Printing message what to enter to help user
    System.out.print("Enter first string : ");
    //taking first string input
    String str1 = input.nextLine();
    //Printing message what to enter to help user
    System.out.print("Enter second string : ");
    //taking second string input
    String str2 = input.nextLine();

    // replace all spaces from targeted string
    str1 = str1.replaceAll("\\s","");
    // replace all spaces from targeted string
    str2 = str2.replaceAll("\\s","");

    //Create a boolean type variable with true value
    boolean status = true;
    //Checking the length of both strings
    //If length of doesn't match it can't be anagram
    if(str1.length() != str2.length()){
      //If string 1 and string 2 length not equals change status value
      status = false;
    }else{
      //f string 1 and string 2 length equals to each other
      //Converting strings into characters array
      char[] char1 = str1.toLowerCase().toCharArray();
      //Converting strings into characters array
      char[] char2 = str2.toLowerCase().toCharArray();
      //Sorting array of characters
      Arrays.sort(char1);
      //Sorting array of characters
      Arrays.sort(char2);
      //checking the equality of both Arrays
      status = Arrays.equals(char1, char2);
    }
    //Checking the status value
    if(status){
      //If status value is true
      System.out.println("STRINGS ARE ANAGRAMS");
    }else{
      //If status value is false
      System.out.println("STRINGS ARE NOT ANAGRAMS");
    }

  }
} 

Output

Enter first string: funeral
Enter second string: real fun
STRINGS ARE ANAGRAMS