Write a Java Program to Check if two strings are anagram

Java Program to Access elements from a LinkedList.

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Check if two strings are anagram
Java Program to Check if two strings are anagram

Write a Java Program to Check if two strings are anagram

PROGRAM: Java Program to Check if two strings are anagram

/*Java Program to Check if two strings are anagram*/

1: Java program to check if two strings are anagrams

import java.util.Arrays;

class Main {
public static void main(String[] args) {
String str1 = “Race”;
String str2 = “Care”;

str1 = str1.toLowerCase();
str2 = str2.toLowerCase();

// check if length is same
if(str1.length() == str2.length()) {

// convert strings to char array
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();

// sort the char array
Arrays.sort(charArray1);
Arrays.sort(charArray2);

// if sorted char arrays are same
// then the string is anagram
boolean result = Arrays.equals(charArray1, charArray2);

if(result) {
System.out.println(str1 + ” and ” + str2 + ” are anagram.”);
}
else {
System.out.println(str1 + ” and ” + str2 + ” are not anagram.”);
}
}
else {
System.out.println(str1 + ” and ” + str2 + ” are not anagram.”);
}
}
}

2: Take string inputs from users and check if the strings are anagram

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

class Main {
public static void main(String[] args) {

// create an object of Scanner class
Scanner input = new Scanner(System.in);

// take input from users
System.out.print(“Enter first String: “);
String str1 = input.nextLine();
System.out.print(“Enter second String: “);
String str2 = input.nextLine();

// check if length is same
if(str1.length() == str2.length()) {

// convert strings to char array
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();

// sort the char array
Arrays.sort(charArray1);
Arrays.sort(charArray2);

// if sorted char arrays are same
// then the string is anagram
boolean result = Arrays.equals(charArray1, charArray2);

if(result) {
System.out.println(str1 + ” and ” + str2 + ” are anagram.”);
}
else {
System.out.println(str1 + ” and ” + str2 + ” are not anagram.”);
}
}
else {
System.out.println(str1 + ” and ” + str2 + ” are not anagram.”);
}

input.close();
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *