This program is simplified for easy understanding using the StringBuilder with reverse function in java.
import java.util.Scanner;
public class Palindrome {
public static void main(String args[]){
//Get the string to check
System.out.println("Enter the string: ");
Scanner sc = new Scanner(System.in);
String inp = sc.nextLine();
sc.close();
//String to string builder to store in heap
StringBuilder sb = new StringBuilder();
sb.append(inp);
//Reverse function over the string
sb = sb.reverse();
String temp = sb.toString();
//compare to check Palindrome
if (inp.equals(temp)){
System.out.println("The given string is a Palindrome.");
}else{
System.out.println("The given string is not a Palindrome.");
}
}
}
Output:
Enter the string: madam
The given string is a Palindrome.
Enter the string: Rajesh
The given string is not a Palindrome.
No comments:
Post a Comment