What is Palindrome? A Palidrome string is a string where if we reverse the string, the word will be same. A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward. Example: madam, refer, redivider The logic in Java for implementation is very simple.,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package my.test; public class Palindrome { public static void main(String[] args) { String string1 = "abcdcba"; String string2 = "abcde"; String string3 = "madam"; String string4 = "refer"; String string5 = "hello"; System.out.println("Is String 1 Palindrome : " + isPalindrome(string1)); System.out.println("Is String 2 Palindrome : " + isPalindrome(string2)); System.out.println("Is String 3 Palindrome : " + isPalindrome(string3)); System.out.println("Is String 4 Palindrome : " + isPalindrome(string4)); System.out.println("Is String 5 Palindrome : " + isPalindrome(string5)); } public static boolean isPalindrome(String str) { String reverseString = ""; if(str!=null && str.length()>0) { char[] charArray = str.toCharArray(); for(int i=charArray.length-1;i>=0;i--){ reverseString = reverseString + charArray[i]; } }else { return false; } System.out.println("Input String: " + str + " , Reversed String: " +reverseString); if(str.equalsIgnoreCase(reverseString)) { return true; } else{ return false; } } } |
Output: Input String: abcdcba … Continue reading “Palindrome String In Java“