In this Java Program, we will learn how to check whether a string is a palindrome or not.
A palindrome is a word, number, phrase, or other sequence of characters that reads the same backward as forward, such as civic or rotator or the number 14241.
A string is a palindrome when we reverse the string and after reversing the string, the reversed string is equal to the original string entered by the user.
Here is the code of the program to check whether a string is a palindrome or not.
In this program, you will see how to Check Whether a Number is Palindrome or Not using For Loop.
//Java Program to Check Whether a String is a Palindrome or Not
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
String str, reversedString = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
str = sc.nextLine();
// closing scanner class(not compulsory, but good programming practice)
sc.close();
int length = str.length();
for (int i = length - 1; i >= 0; i--)
reversedString = reversedString + str.charAt(i);
if (str.equals(reversedString)) {
System.out.println(str + " is a palindrome");
} else {
System.out.println(str + " is not a palindrome");
}
}
}
Enter a string:
rada
rada is not a palindrome
Enter a string:
civic
civic is a palindrome
In this program, you will see how to Check Whether a Number is Palindrome or Not using Recursion.
//Java Program to Check Whether a String is a Palindrome or Not Using Recursion
import java.util.Scanner;
public class JavaPrograms {
// Recursive function to check if `str[low…high]` is a palindrome or not
public static boolean isPalindrome(String str, int low, int high) {
// base case
if (low >= high) {
return true;
}
// return false if mismatch happens
if (str.charAt(low) != str.charAt(high)) {
return false;
}
// move to the next pair
return isPalindrome(str, low + 1, high - 1);
}
public static void main(String[] args) {
String str;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
str = sc.nextLine();
// closing scanner class(not compulsory, but good programming practice)
sc.close();
if (isPalindrome(str, 0, str.length() - 1)) {
System.out.print(str + " is a Palindrome");
} else {
System.out.print(str + " is a Not Palindrome");
}
}
}
Enter a string:
rada
rada is not a palindrome
Enter a string:
civic
civic is a palindrome
Comments