In this shot, we will discuss how to check whether a string is a palindrome or not in Java. A palindrome is a string that reads exactly the same, whether it is read from left to right or right to left.
“madam” is a palindromic string because it reads the same forwards and backward. Other palindromic strings are “anna,” “civic,” “level,” “mom,” “noon,” and “racecar.”
However, if we take a different example like “programmer,” it reads differently if we read it forward and backward. Therefore, “programmer” is not a palindrome.
We can use the isPalindrome()
function to check if a string is a palindrome. We pass our input string as an argument and the function will return true
if the string is a palindrome and false
otherwise.
Let’s look at the code below to better understand.
import java.util.Scanner;class palindrome {public static void main(String[] args) {Scanner scanner=new Scanner(System.in);System.out.println("Enter a string as an input to check whether it is palindrome or not");String input= scanner.nextLine();//checking whether palindrome or notif(isPalindrome(input)){System.out.println(input+" is a palindrome string");}else{System.out.println(input+" is not a palindrome string");}}public static boolean isPalindrome(String str) {int left = 0, right = str.length() - 1;while(left < right){if(str.charAt(left) != str.charAt(right)){return false;}left++;right--;}return true;}}
Enter the input below
Enter a string in the input section to generate an output.
In line 1 we import the java.util.Scanner
class to read input from the user.
In line 7 inside the main
function, we create a Scanner
object to take the input string from the user and store that input in a String
input variable.
In line 9 we call the isPalindrome()
function, which returns true
if the input is actually a palindrome.
In lines 19 to 31 we define the isPalindrome()
function. In this function, we initiate two indexes, left
and right
, and give the values 0
and str.length()-1
, repectively.
Then, we run a while
loop until the left index is less than the right index, and compare the character at the left index and the character at the right.
If the characters are not equal at any point, we return false
; otherwise, we return true
.
We can also check of the string is a palindrome, using StringBuilder reverse()
method.
class palindrome {public static boolean isPalindrome(String str) {StringBuilder reversed = new StringBuilder(str).reverse();return str.equals(reversed.toString());}public static void main(String[] args) {String value = "racecar";if (isPalindrome(value)) {System.out.println(value + " is a palindrome string.");} else {System.out.println(value + " is not a palindrome string.");}}}
Line 3: We create a StringBuilder
object with the input string and reverse it.
Line 4: Here, we check if the original string is equal to the reversed string.
Line 9-13: Here, we check if the test string is a palindrome or not and print the result.