A palindrome is a word which reads the same backward as forward
For Example : MADAM
Approach :
Here i am using Java Builder Class to perform the task. It is used to create mutable (which can be changed) Strings. We will be using StringBuilder insert() method to reverse the string and check if its palindrome or not. The StringBuilder insert() method inserts the given string with this string at the given position.
Java Python
Code :
import java.util.Scanner;
public class palindrome {
public static void main(String[] args) {
StringBuilder temp = new StringBuilder();
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Word : ");
String word = sc.next();
for (int i = 0; i < word.length(); i++) {
char r = word.charAt(i);
temp.insert(0, r);
}
if (word.equals(temp.toString())){
System.out.println(word+" is palindrome");
}
else {
System.out.println(word+" is not palindrome");
}
}
}
Output :
CASE 1 : When a String is palindrome
Enter a Word :
madam
madam is palindrome
CASE 2 : When a String is not palindrome
Enter a Word :
abhay
abhay is not palindrome
Explanation :
Declare Scanner and String Builder Objects
Take a String input from the user
initialize a for loop within the range from 0 to length of string
extract the character at the index using charAt() method and insert it into temp
Rest is simple create a if-else block and check if the String is palindrome or not
0 Comments
Ask Your Queries in the comments