- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to check whether two Strings are an anagram or not.
According to wiki “An anagram is word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.”
To compare whether two strings are anagrams check if their lengths are equal? If so, convert these two strings into character arrays then, sort them and compare them using the sort() method of the Arrays class, if both are equal then given two strings are anagrams.
Example
import java.util.Arrays; public class AnagramSample { public static void main(String args[]) { String str1 = "recitals"; String str2 = "articles"; if (str1.length()==str2.length()) { char[] arr1 = str1.toCharArray(); Arrays.sort(arr1); System.out.println(Arrays.toString(arr1)); char[] arr2 = str2.toCharArray(); Arrays.sort(arr2); System.out.println(Arrays.toString(arr2)); System.out.println(Arrays.equals(arr1, arr2)); if(arr1.equals(arr2)) { System.out.println("Given strings are anagrams"); } else { System.out.println("Given strings are not anagrams"); } } } }
Output
[a, c, e, i, l, r, s, t] [a, c, e, i, l, r, s, t] true Given strings are not anagrams
- Related Articles
- Java Program to Check if two strings are anagram
- Golang Program to Check if two Strings are Anagram
- Check whether two strings are anagram of each other in Python
- C Program to check if two strings are same or not
- Golang Program to Check Whether Two Matrices are Equal or Not
- Swift Program to Check Whether Two Matrices Are Equal or Not
- Check whether two strings are equivalent or not according to given condition in Python
- C# program to check whether two sequences are the same or not
- Program to check whether two sentences are similar or not in Python
- Program to check whether two string arrays are equivalent or not in Python
- Java program to check if binary representations of two numbers are anagram
- Program to check whether final string can be formed using other two strings or not in Python
- Java Program to check whether a file exists or not
- Program to check two strings are 0 or 1 edit distance away or not in Python
- Check if two strings are anagram of each other using C++

Advertisements