Table of Contents
In this article, we will see how to implement palindrome program in java.
A palindrome is a word, phrase, number, or other sequence of symbols or elements that reads the same forward or reversed.
For example: 12121 is palindrome as it reads same forward or reversed. madam is also a palindrome .
This is very simple interview question.There are many ways to check if given string is palindrome or not.
Reversing a String and then comparing it with input String:
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 |
package org.arpit.java2blog; import java.util.Scanner; public class StringFullLoopPalindrome { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter string : "); String str = scanner.nextLine(); String reverseStr = ""; for(int i = str.length() - 1; i >= 0; i--){ reverseStr = reverseStr + str.charAt(i); } if(str.equals(reverseStr)){ System.out.println("String is palindrome"); } else { System.out.println("String is not palindrome"); } } } |
1 2 3 4 5 6 |
Enter string : 12121 String is palindrome Enter a string : Apple String is not palindrome |
Using half loop,Moving from both end of String simultaneously:
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 org.arpit.java2blog; import java.util.Scanner; public class StringUsingHalfLoop { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string : "); String str = scanner.nextLine(); boolean isPalin=isPalindrome(str); if(isPalin) System.out.println("String is Palindrome"); else System.out.println("String is not Palindrome"); } static boolean isPalindrome(String str) { for (int i = 0,j=str.length()-1; i <str.length()/2; i++,j--) { if(str.charAt(i)!=str.charAt(j)) { return false; } } return true; } } |
1 2 3 4 5 6 |
Enter a string : madam String is Palindrome Enter a string : adam String is not Palindrome |
Using StringBuilder’s reverse() function:
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 |
package org.arpit.java2blog; import java.util.Scanner; public class StringPalindrome { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter string : "); String str = scanner.nextLine(); StringBuilder strBuilder = new StringBuilder(str); strBuilder.reverse(); if(str.equals(strBuilder.toString())){ System.out.println("String is palindrome"); } else { System.out.println("String is not palindrome"); } } } |
1 2 3 4 5 6 |
Enter a string : stats String is palindrome Enter a string : 1212121 String is palindrome |
That’s all about palindrome program in java.
You can also check Python program to check if String is palindrome.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.