Palindrome or not using Java

Palindrome or not using java :

 

In this article, we will create a java program to check whether a string entered by the user is Palindrome or not. Here we will ask the user to enter a string and then by the help of the java code we will reverse the string and then check that the reversed string is equal to the original string or not. If the reversed string is equal to the original string then the string is Palindrome , otherwise the string is not Palindrome

For better understanding let’s consider some examples :

  1. 1900 : 

Reverse of 1900 is 0091, but 0091 is not equal to 1900, hence the string is not Palindrome.

      2. NAMAN :

Reverse of NAMAN is NAMAN, hence the reversed string is equal to the original string, so the string is Palindrome.

Palindrome or not using Java

Working :

Step 1 : Ask the user to enter a string.

Step 2 : Calculate the length of the string.

Step 3 : Declare a string variable to store reversed string.

Step 4 : Use a loop to perform continuous iterations till the length of the string.

Step 5 : Pick out each character of the string by using charAt() function one by one and store in the declared string variable in reverse order.

Step 6 : Repeat Step 4 till the condition of the loop do not get false.

Step 7 : Use a condition to check that reversed string is equal to the original string or not. If this condition gets true then display the message that the string entered by you is Palindrome, otherwise display the message that the string entered by you is not Palindrome.

Code in Java :

//Java program to check whether a string entered by user is palindrome or not.
import java.util.Scanner;
public class palindrome_or_not
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a String : ");
String st = sc.next();
//string function for calculating length of the string
int len = st.length();
//string variable to store reversed string
String st1 = "";
for(int i = 0 ; i < len ; i++)
{
//string function for getting character at a particular index
char ch = st.charAt(i);
st1 = ch + st1;
}
//condition for checking palindrome by using string function
if(st.equals(st1))
System.out.print("Palindrome");
else
System.out.print("Not Palindrome");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter a String : NAMAN

Palindrome


Enter a String : 12321

Palindrome


Enter a String : 12e23

Not Palindrome

2 comments on “Palindrome or not using Java”