Palindrome Program in Java

What is a Palindrome?

A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. In other words, it remains unchanged when its characters are reversed. For example, words like "radar," "level," and "madam" are palindromes, as well as phrases like "Able was I ere I saw Elba." Palindromes are a common topic in wordplay and are often used as puzzles or in games.

Here are a few examples:

  1. abba
  2. refer
  3. kayak
  4. racecar

Palindrome Program in Java

Following is a Java program to check if a string is a palindrome:

import java.util.Scanner; public class PalindromeChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); if (isPalindrome(input)) { System.out.println("\"" + input + "\" is a palindrome."); } else { System.out.println("\"" + input + "\" is not a palindrome."); } scanner.close(); } public static boolean isPalindrome(String str) { int left = 0; int right = str.length() - 1; while (left < right) { if (str.charAt(left) != str.charAt(right)) { return false; } left++; right--; } return true; } }

In this program, we first take input from the user for the string to be checked. Then, we call the isPalindrome() method to determine whether the string is a palindrome or not.

The isPalindrome() method checks if the characters at the left and right ends of the string are the same. If they are not the same, then the string is not a palindrome, and the method returns false. Otherwise, it continues checking the next pair of characters towards the center of the string. If all the characters are the same from both ends, the method returns true, indicating that the string is a palindrome.


Java Palindrome

Conclusion

You can run this program and input different strings to check if they are palindromes or not. For example, entering "radar" will produce the output: "radar is a palindrome", while entering "hello" will produce the output: "hello is not a palindrome".