
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Palindrome String in Java
In this article, we will learn how to check whether a string is a palindrome in Java. A palindrome reads the same forward and backward. By using the StringBuffer class and its reverse() method.
Problem Statement
Given a string, write a Java program to check if it is a palindrome by reversing the string and comparing it with the original.Input
"anna"Output
Given String is palindrome
Steps to check if a string is a palindrome
The following are the steps to check if a string is a palindrome ?
- Create a StringBuffer object by passing the string.
- Use the reverse() method to reverse the string.
- Convert the reversed StringBuffer to a String.
- Compare the original string with the reversed one. If they match, it's a palindrome.
Java program to check if a string is a palindrome
The following is an example of checking if a string is a palindrome ?
public class StringPalindrome { public static void main(String args[]) { String myString = "anna"; StringBuffer buffer = new StringBuffer(myString); buffer.reverse(); String data = buffer.toString(); if(myString.equals(data)) { System.out.println("Given String is palindrome"); } else { System.out.println("Given String is not palindrome"); } } }
Output
Given String is palindrome
Code Explanation
The program creates a StringBuffer object with the given string and reverses it. It then converts the reversed content to a String. Finally, it compares the original and reversed strings. If they are equal, the program prints that the string is a palindrome.Advertisements