December 30, 2014

Java program to check a string is palindrome

How to check whether a string is palindrome

Palindorme in java source code : Palindrome are strings, that remains unchanged even when reversed for example "mom","malayalam",etc







import java.util.Scanner;

/**
 * Worldcup cricket 2015
 */

/**
 * @author Moto
 *
 */
public class Palindrome {

    /**
     * @param args
     */
    public static void main(String[] virat) {
        // TODO Auto-generated method stub
        Palindrome palindromeNumber = new Palindrome();
        palindromeNumber.checkPalindrome();

    }

    private void checkPaliandrome() {
        // TODO Auto-generated method stub
        String str = null;
        System.out.println(" Please enter the string that you want to check is that a paliandrome");
        Scanner scanner = new Scanner(System.in);
        str = scanner.next();
        //str= "worldcupcricketekcircpucdlrow";  //test value
        //System.out.println(str);
        int len = str.length();
        System.out.println(len);
        int first =0;
        int last =len-1;
        int flag = 0;
        int loopLen = len/2;
        //System.out.println(str.charAt(first));
        //System.out.println(str.charAt(last));
      
        for(int count=0;count<loopLen;count++){
          
            if(str.charAt(first)!=str.charAt(last)){
                flag =1;
                break;
            }
              
          
            //System.out.println(str.charAt(first)+"--"+str.charAt(last));
            first=first+1;
            last=last-1;
        }
      
        String output = flag ==0? " paliandrome" : "not a paliandrome";
        System.out.println(str+ " is "+output);
    }

}

 

 if you want to know how to use ternary operator please visit this link
http://javabelazy.blogspot.in/

Facebook comments