In this tutorial you will learn about the Java Program to Check Whether Given String is a Palindrome and its application with practical example.
In this tutorial, we will learn to create a Java program that will check Given String is a Palindrome or Not using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following java programming topics:
- Java Operators.
- Basic Input and Output
- Class and Object.
- Basic Java programming.
- String.
- User define Function.
What Is Palindrome of String?
A palindrome occur’s when a String that reads the same way as backward and forward.
Example : dad , nayan , pop, abcba and etc…
As you see above all the string either forward or backward gives the same meaning are called as a Palindrome String.
Java Program to Check Whether Given String is a Palindrome
In this program we will Check Whether Given String is a Palindrome or not. We would first declared and initialized the required variables. Next, we would assign values to the variables . Later we will Find string is palindrome or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Revese_String { public static void main(String[] args) { String s = "DAD", revStr = ""; //Declaring variables... int strngLength = s.length(); //Finding length of string// for (int i = (strngLength - 1); i >=0; --i) { revStr = revStr + s.charAt(i); // reversing a string } if (s.equals(revStr)) //Comparing string { System.out.println(s + " is Palindrome."); } else { System.out.println(s + " is not Palindrome "); } } } |
Output
Palindrome string….
Not a a Palindrome String..
In the above program, we have first declared and initialized a set variables required in the program.
- s =it will hold given string.
- revStr= it wil hold revese String.
- i= for iteration.
- strnglength = it will hold length of string.
In the first statement we will assign string to variable ‘s’.
after this with the help of length() function we find the length of entered string.
Now using loop in we reverse the string and after that we compare this string to original string
Now we will check condition for palindrome of a string, which, when read in both forward and backward ways is the same.
If any above condition we checking, the original string to which we reverse and condition became true we will get Palindrome String and if condition falls we will get not a palindrome String