Monday, 29 June 2015

Reverse a String and check for Plindrome String

package com.JavaInterview.Programs;
/*
 * 
 */
import java.util.*;
public class RevString1 {

 public String rev = "";

 public String revString(String s) {

  if (s.length() == 1) {
   return s;
  } else {
   for(int i=s.length()-1;i>=0;i--){
   rev = rev + s.charAt(i);
   }
   return rev;
  }
 }

 public static void main(String args[]) {
 
  Scanner input=new Scanner(System.in);
  System.out.println("Please enter the string :");
 
  String s=input.nextLine();
  RevString1 r = new RevString1();
 /****Line 19 *****/
  System.out.print("Reverse of String "+ s+" is :"+r.revString(s));

 }

}

/****For PALINDROME String replace lines after line 19 with ****/
        
         String rev = r.revString(s);
  if (rev.equals(s) {
   System.out.println("The String " + s + " is a Palindrome");
  } else {
   System.out.println("The String " + s + " is NOT aPalindrome");
  }
}

Output :
Please enter the string :
INDIA
Reverse of String INDIA is :AIDNI

Output :
Please enter String 
paqjqap

The String paqjqap is a Palindrome


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...