Write a Java program to Check Palindrome or Not
The code checks whether a string is a palindrome or not. Let's understand the code step by step:
- The code starts with the import statements import java.util.Stack; and import java.util.Scanner; . These import the Stack class from the java.util package and the Scanner class from the java.util package, respectively.
- The Palindrome_Check class is defined, serving as the entry point of the program.
- In the main method, a Scanner object named input is created to read input from the user.
- The user is prompted to enter a string by using the System.out.print statement.
- The user's input is read and stored in the str variable using the nextLine method of the Scanner class.
- The isPalindrome method is called, passing the str as an argument. The return value of the isPalindrome method is stored in the isPalindrome variable.
- The System.out.println statement is used to print whether the string is a palindrome or not by concatenating the string "Is Palindrome ? " with the value of the isPalindrome variable.
- The isPalindrome method is defined, which takes a string (str) as a parameter and returns a boolean value indicating whether the string is a palindrome or not.
- In the isPalindrome method, a stack object named stack is created using generics, specifying that it will contain characters (Character).
- A foreach loop is used to iterate over each character in the str string. Each character is pushed onto the stack using the push method.
- A StringBuilder object named rev is created to store the reversed string.
- A while loop is used to pop characters from the stack until it is empty. Each popped character is appended to the rev using the append method.
- The method compares the original string (str) with the reversed string (rev.toString()) using the equals method of the String class.
- If the original string and the reversed string are equal, the method returns true, indicating that the string is a palindrome. Otherwise, it returns false.
Source Code
import java.util.Stack;
import java.util.Scanner;
public class Palindrome_Check
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String : ");
String str = input.nextLine();
boolean isPalindrome = isPalindrome(str);
System.out.println("Is Palindrome ? " + isPalindrome);
}
public static boolean isPalindrome(String str)
{
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray())
{
stack.push(c);
}
StringBuilder rev = new StringBuilder();
while (!stack.isEmpty())
{
rev.append(stack.pop());
}
return str.equals(rev.toString());
}
}
Output
Enter the String : madam
Is Palindrome ? true