Skip to main content

Java program to check to weather the program palindrome or not.

                Let us see the java program to check the string is palindrome or not. so first we should know about palindrome. and logic to write a program, get to know about them below.

Content.
  1. What is palindrome the string.
  2. Logic for program.
  3. Program.
  4. Explanation.
  5. Output.


What is palindrome the string?
             Palindrome string means if we give a number like 858, when the number is palindrome we should get same number, 858.
Example:
                    our Input: malayalam
                       Output: malayalam


Logic for the Program.
  • We need to display the last string first.
  • So, when we use that in a loop, to get the Reversed string.
  • And check whether the reversed string is equal to the given string, if it is equal, then string is palindrome. If not, it is not a palindrome.


Program

import java.io.*;
public class expal
{
  public static void main(String args[]) throws IOException
   {
     String A, B="";
     int x,y;
     char c;
     InputStreamReader read=new InputStreamReader(System.in);
     BufferedReader in = new BufferedReader(read);
     System.out.println("Enter the string");
     A=in.readLine();
     x=A.length();
       for(y=0;y<x;y++)
        {
          c=(A.charAt(y));
          B=c+B;
        }
      if(A.compareTo(B)==0)
         System.out.println("Given string is palindrome=" +A);
   else
         System.out.println("given string is not a palindrome=" +A);
   }
}


Explanation.
  • We have given the class name has exrev.
  • public static void main(String arg[]) refers to add a method i.e array of strong method to the program.
  • String A,B, int x,y, char c is declaring the variable, s is declared to store 0. 
  • InputStreamReader read = new InputStreamReader(System.in); we create this object because we need to give the value to variable at the time of execution, this is a one of the way to give value to a variable.
  • BufferedReader in = new BufferedReader(read); we create this object because, we need a buffer to store the value of the variable.
  • Now, we have to give condition which satisfies all the above int the logic for the program. I choose,  for loop with y=0,y<x,y++ as condition.
  • is the string we give, B is reversed string.
  • And check if the given string is equal to reveresed string. 
  • System.out.println is used to display the given in output screen(make sure S in System is capital)
Know more about if statement.
Know more about for loop here.

Output:

       Compile : javac expal.java
       Run        : java expal
       Enter the number
       madam
      The given number is palindrome, madam.

      Compile : javac expal.java
       Run        : java expal
       Enter the number
        java
      The given number is not palindrome, avaj.



Comments