Java program to check if a string is a palindrome or not, it’s a palindrome if it remains the same on reversal.
For example, “dad” is a palindrome, as its reverse is “dad,” whereas “program” isn’t, as its reverse is “margorp” that is different from “program.”
Some palindrome strings examples are: “j”, “mom”, “madam”, “ab1ba”, “12321.”
In the program, a user inputs a string, and we create a new one by reversing it and then compares it with the input string.
Java Code: Palindrome Program in Java using Reverse Method
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 |
import java.util.Scanner; public class JavaExamples2 { public static void main(String[] args) { String original; // Objects of String class StringBuffer reverse; Scanner in = new Scanner(System.in); System.out.println("Enter a string to check if it's a palindrome"); original = in.nextLine(); //reverse method reverse = new StringBuffer(original); reverse.reverse(); System.out.println(reverse); if (original.equals(reverse.toString())) System.out.println("The string is a palindrome."); else System.out.println("The string isn't a palindrome."); } } |
Output:
1 2 3 4 5 6 |
Enter a string to check if it's a palindrome 123321 123321 The string is a palindrome. |