Thursday, 8 May 2014

Java program to check whether string is palindrome or not

Java program to check whether string is palindrome or not works as  follows : 
In first step we take a sting and its length. We traverse the sting on both the side simultaneously, like 1st character of the sting is compared with last character of the sting so if that matches then continue the loop Otherwise just break the loop, come out of the loop and print the respective message. Here are the some palindrome strings examples:  "madam", "dad" etc.. 

Here you can find two versions of program where first one is same which explained earlier and second version is of reverse pattern. The reverse  version starts with getting the length of the string as int end=st1.length()-1; . The for is trick here we starts from the end to beginning and check the character. 
 

Version : 1


 import java.util.*;   
  import java.lang.*;   
  class PalindromeProgram   
  {    
   public static void main(String args[])   
   {   
  String st1="aba";   
  int end=st1.length()-1;   
  int flag=0;   
    for (int j=0;j<=end;j++)   
    {   
     if (st1.charAt(j)!=st1.charAt(st1.length()-j-1))   
     {   
     flag=1;   
     break;   
     }   
    }  
  if(flag==1)   
  System.out.printf("'%s' string is not a palindrome",st1);   
  else   
  System.out.printf("yes,'%s' string is palindrome",st1);   
   }   
  }   

Version : 2

 import java.util.*;  
 import java.lang.*;  
 class ReverseVersion  
 {   
   public static void main(String args[])  
   {  
    String st1="aba";   
    int end=st1.length()-1;   
    int flag=0;   
    String copy="";   
    for (int j=end;j>=0;j--)   
    {   
     copy=copy+st1.charAt(j);   
    }   
    System.out.printf("\nOriginal string : %s",st1);   
    System.out.printf("\nReversed string : %s\n",copy);   
    if(st1.equals(copy))   
    System.out.printf("yes,'%s' string is palindrome",st1);   
    else   
    System.out.printf("'%s' string is not a palindrome",st1);   
   }   
 }   


No comments:
Write comments

Featured post

List of Universities in Karnataka offering M.Sc Computer Science

The post-graduate programme in Computer Science (M.Sc Computer Science) contains two academic years duration and having a four semesters....

Popular Posts

Copyright @ 2011-2016