English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will check if two strings are anagrams (anagrams) in Java, a new word formed by rearranging the letters of a word or sentence.
If we can form a string by rearranging the characters of another string, then we can say that the two strings are a jigsaw. For example,Race With Care。Here, we can rearrange the letters of Care to form the word Race.
import java.util.Arrays; class Main { public static void main(String[] args) { String str1 = "Java"; String str2 = "Vaaj"; //Check if the lengths are the same if(str1.length() == str2.length()) { //Convert the string to a character array char[] charArray1 = str1.toCharArray(); char[] charArray2 = str2.toCharArray(); //Sort the character arrays Arrays.sort(charArray1); Arrays.sort(charArray2); //If the sorted character arrays are the same //Then the string is an anagram boolean result = Arrays.equals(charArray1, charArray2); if(result) { System.out.println(str1 + " and " + str2 + " is an anagram."); } else { System.out.println(str1 + " and " + str2 + " is not an anagram."); } } } }
Output Result
Java and Vaaj are anagrams
In Java, we have two strings named str1and str2Here, we check if str1and str2whether they have the same letters but in a different order.
Here,
str1.toCharArray() - Convert the string to a char array
Arrays.sort() - Sort the two character arrays
Arrays.equal() - Check if the sorted char arrays are equal
If the sorted arrays are equal, then the strings are anagrams.
import java.util.Arrays; import java.util.Scanner; class Main { public static void main(String[] args) { //Create an object of the Scanner class Scanner input = new Scanner(System.in); //Accept user input System.out.print("Enter the first string: "); String str1 = input.nextLine(); System.out.print("Enter the second string: "); String str2 = input.nextLine(); //Check if the lengths are the same if(str1.length() == str2.length()) { //Convert the string to a char array char[] charArray1 = str1.toCharArray(); char[] charArray2 = str2.toCharArray(); //Sort the char array Arrays.sort(charArray1); Arrays.sort(charArray2); //If the sorted char array is the same //Then the string is an anagram boolean result = Arrays.equals(charArray1, charArray2); if(result) { System.out.println(str1 + " and " + str2 + " is an anagram."); } else { System.out.println(str1 + " and " + str2 + " is not an anagram."); } } input.close(); } }
Output Result
Enter the first string: Race Enter the second string: Care Race and Care are anagrams
In the above example, we useScannerThe class gets input from the user. Here, we check if the string provided by the user is an anagram.