Home » Java programs » Java string programs

Java program to check given strings are Anagram or not

This java program will read two strings and check whether they are anagram strings or not.

package com.includehelp.stringsample;

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

/**
 * program to check given strings are Anagram or not
 */
public class AnagramString {
    
    /**
     * Method to check two strings are anagram string or not
     * @param str1
     * @param str2
     * @return 
     */
    static boolean isAnagrams(String str1,String str2){
        if(str1.length()!=str2.length()){
            return false;
        }
        char[] strArray1 = str1.toCharArray();
        char[] strArray2 = str2.toCharArray();
                
        Arrays.sort(strArray1);
        Arrays.sort(strArray2);
       
        String sortedStr1 = new String(strArray1);
        String sortedStr2 = new String(strArray2);
       
        if(sortedStr1.equals(sortedStr2)){
            return true;
        }
        else{
            return false;
        } 
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter String1 : ");
        String str1 = sc.next();
        System.out.println("Enter String2 : ");
        String str2 = sc.next();
        
        
        if(isAnagrams(str1,str2)){
            System.out.println("Anagram Strings !!");
        }
        else{
            System.out.println("Strings are not Anagram !!");
        }
    }
}

Output

First run:
Enter String1 : john
Enter String2 : nohj
Anagram Strings !!

Second run:
Enter String1 : John
Enter String2 : Marry
Strings are not Anagram !!





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.