0
Sponsored Links


Ad by Google
Nowadays in any interview beat experienced or fresher you will face at least 2-3 coding interview question as part of first round of technical written interview. And to checking string is palindrome or not is one of the popular coding interview question like balancing a parentheses or finding factorial of given number. So i would suggest everyone to do practice on such coding questions.
Although, I have separately posted a complete set-up of Java interview questions here and in this post going to show you a simple Java program to check if string is palindrome or not.

Code to check if string is palindrome or not
package com.javamakeuse.poc;

/**
 * 
 * @author javamakeuse
 *
 */
public class Palindrome {
 public static boolean isPalindrome(String s) {
  int n = s.length();
  for (int i = 0; i < (n / 2); ++i) {
   if (s.charAt(i) != s.charAt(n - i - 1)) {
    return false;
   }
  }

  return true;
 }

 public static boolean isPalindrome2(String str) {
  if (str.equals(new StringBuilder(str).reverse().toString())) {
   return true;
  }
  return false;

 }

 public static void main(String[] args) {
  System.out.println(isPalindrome("696"));
  System.out.println(isPalindrome("java"));
  System.out.println(isPalindrome2("POP"));
 }
}

OUTPUT:
true
false
true

Sponsored Links

0 comments:

Post a Comment