Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Sentence Palindrome
Next article icon

Java Program to Check Whether a String is a Palindrome

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A string in Java can be called a palindrome if we read it from forward or backward, it appears the same or in other words, we can say if we reverse a string and it is identical to the original string for example we have a string s = “jahaj ” and when we reverse it s = “jahaj”(reversed) so they look identical so we can say that “jahaj” is a palindrome string. In this article, we will go through different approaches to check if a string is a palindrome in Java. 

Example Input/Output:

Input: s = “level”
Output: True

Input: s = “Geeks”
Output: True

Input s = “G”
Output: True.

Brute Force Approach

The brute force or naive approach to check if a string is a palindrome is by reversing the string, and then we can compare it with the original. Here, to ensure the comparison is case-insensitive, the string is converted to lowercase before the check. For example, if we do not convert the string to lowercase so it won’t work with the different cases, such as Level and level, it will give false, but it is a palindrome.

Algorithm:

  • First, convert the string to lowercase to ensure a case-insensitive comparison.
  • Reverse the string using a loop.
  • Compare the original string with the reversed String. If both are equal, then it is a palindrome. Otherwise, it is not.

Example: Java program to check whether a string is a palindrome by comparing it with its reversed string.

Java
// Java Program to Check if a  // String is a Palindrome import java.io.*;  public class Geeks {      // Method to check if a string is a palindrome     public static boolean isPalindrome(String s) {                // Convert string to lowercase for          // case-insensitive comparison         s = s.toLowerCase();          // Reverse the string         String rev = "";         for (int i = s.length() - 1; i >= 0; i--) {             rev = rev + s.charAt(i);         }          // Compare the original string with          // the reversed string         return s.equals(rev);     }      public static void main(String[] args) {                // Input string         String s = "level";          // Check if the string is a palindrome         boolean res = isPalindrome(s);          // Print the result with enhanced output         if (res) {             System.out.println('"' + s + '"' + " is a palindrome.");         } else {             System.out.println('"' + s + '"' + " is not a palindrome.");         }         }     } 

Output
"level" is a palindrome. 

Explanation: In the above example, It checks if the given string is palindrome by converting it to lowercase, reversing it, and then comparing the reversed string with the original.

  • Time Complexity: O(n)
  • Space Complexity: O(n)

Table of Content

  • Other Methods to Check a String Palindrome
    • Two Pointer Approach to Check if incrementa String Is Palindrome
    • Recursive Approach to Check if a String is Palindrome
    • StringBuilder Approach to Check a String is Palindrome

Other Methods to Check a String Palindrome

1. Two Pointer Approach to Check if incrementa String Is Palindrome

This approach uses two pointers, one starting at the beginning “i” and the other at the end “j" of the string. By comparing characters at these pointers and moving them inward, we can determine if the string is a palindrome or not.

Algorithm:

  • We initialize two pointers (i=0) from the start and (j = s.length -1) from the end.
  • Compare the characters at index i and j, if both are not equal then return false( it is not a palindrome).
  • If they match then increment i by 1 and decrement j by 1 and continue the process.
  • If all the characters match and the loop stops at ( i = j), then it is a palindrome and returns true.

Example:

Java
// Java program to check whether a // string is a Palindrome // Using two pointing variables public class Geeks {     // Method to check if a string is a palindrome     public static boolean isPalindrome(String s) {         int i = 0, j = s.length() - 1;          // Compare characters while i < j         while (i < j) {             if (s.charAt(i) != s.charAt(j)) {                 return false;                   }             i++;             j--;         }         return true;           }      public static void main(String[] args) {                // Input strings         String s1 = "geeks";         String s2 = "Racecar";          // Convert strings to lowercase for          // case-insensitive comparison         s1 = s1.toLowerCase();         s2 = s2.toLowerCase();          // Check and print results for s1         if (isPalindrome(s1)) {             System.out.println("\"" + s1 + "\" is a palindrome.");         } else {             System.out.println("\"" + s1 + "\" is not a palindrome.");         }          // Check and print results for s2         if (isPalindrome(s2)) {             System.out.println("\"" + s2 + "\" is a palindrome.");         } else {             System.out.println("\"" + s2 + "\" is not a palindrome.");         }     } } 

Output
"geeks" is not a palindrome. "racecar" is a palindrome. 

Explanation: In this example, the isPalindrome method checks for mismatched characters while i < j and returns false if found. The main method converts input strings to lowercase and prints whether they are palindrome.

  • Time Complexity: O(n)
  • Space Complexity: O(1)

2. Recursive Approach to Check if a String is Palindrome

Now for recursion we are using the same approach as we used in the two pointer, here we create two pointer I from start and j from the end in the recursion. and Increaement the i by one and decrement j by 1, if the characters at the index i not match the character present at index j then it is not a palidrome if it the base condition hit i=j and

Algorithm:

  • We will take two pointers, “i” pointing to the start of the string and “j” pointing to the end of the string. 
  • Base Case: If i >= j, the recursion stops, as the string has been fully checked, and it is confirmed to be a palindrome.
  • Character Comparison: Check if the characters at positions i and j are equal.
    • If not, return false immediately (the string is not a palindrome).
    • If they match, make a recursive call with the next set of indices (i + 1 and j – 1).
  • The recursion continues until the base case is satisfied.

If all characters match until the pointers meet or cross, the string is a palindrome. Otherwise, it is not.

Example:

Java
// Java program to check whether a // string is a Palindrome using recursion public class Geeks {     // Recursive method to check      // if a string is a palindrome     public static boolean isPalindrome(int i, int j, String s) {                // If pointers have crossed,          // it's a palindrome         if (i >= j) {             return true;         }          // If characters at i and j are not the same,          // return false         if (s.charAt(i) != s.charAt(j)) {             return false;         }          // Recursive call for the          //next pair of pointers         return isPalindrome(i + 1, j - 1, s);     }      // Overloaded method to simplify the call     public static boolean isPalindrome(String s) {         return isPalindrome(0, s.length() - 1, s);     }      public static void main(String[] args) {                // Input strings         String s1 = "geeks";         String s2 = "Racecar";          // Convert strings to lowercase for          // case-insensitive comparison         s1 = s1.toLowerCase();         s2 = s2.toLowerCase();          // Check and print results for s1         if (isPalindrome(s1)) {             System.out.println("\"" + s1 + "\" is a palindrome.");         } else {             System.out.println("\"" + s1 + "\" is not a palindrome.");         }          // Check and print results for s2         if (isPalindrome(s2)) {             System.out.println("\"" + s2 + "\" is a palindrome.");         } else {             System.out.println("\"" + s2 + "\" is not a palindrome.");         }     } } 

Output
"geeks" is not a palindrome. "racecar" is a palindrome. 
  • Time Complexity: O(n)
  • Space Complexity: O(n)

3. StringBuilder Approach to Check a String is Palindrome

In this approach, we will use the StringBuilder class to reverse a string and compare it with the original string. Below are the steps:

  • First we create an object of StringBuilder using the input string.
  • Then we use the reverse() method of StringBuilder class to reverse the string.
  • Now, convert the reversed string back to a String using the method toString().
  • Compare the reversed string with the original string using the equals() method.
  • If the equals method returns true then it is a palindrome otherwise it is a not a palindrome.

Example:

Java
// Java program to check if a  // string is a palindrome using StringBuilder public class Geeks {     public static void main(String[] args) {                // Input string         String s = "GeeksForGeeks";          // Create a StringBuilder object          //with the original string         StringBuilder s1 = new StringBuilder(s);          // Reverse the string          // using the reverse() method         s1.reverse();          // Compare the reversed string          // with the original string         if (s.equals(s1.toString())) {             System.out.println("\"" + s + "\" is a palindrome string.");         } else {             System.out.println("\"" + s + "\" is not a palindrome string.");         }     } } 

Output
"GeeksForGeeks" is not a palindrome string. 
  • Time Complexity: O(n)
  • Space Complexity: O(n)


Next Article
Sentence Palindrome

S

samarthbais255
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-String-Programs
  • Java-Strings
Practice Tags :
  • Java
  • Java-Strings

Similar Reads

  • Palindrome String Coding Problems
    A string is called a palindrome if the reverse of the string is the same as the original one. Example: “madam”, “racecar”, “12321”. Properties of a Palindrome String:A palindrome string has some properties which are mentioned below: A palindrome string has a symmetric structure which means that the
    2 min read
  • Palindrome String
    Given a string s, the task is to check if it is palindrome or not. Example: Input: s = "abba"Output: 1Explanation: s is a palindrome Input: s = "abc" Output: 0Explanation: s is not a palindrome Using Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left)
    14 min read
  • Check Palindrome by Different Language

    • Palindrome Number Program in C
      Write a C program to check whether a given number is a palindrome or not. Palindrome numbers are those numbers which after reversing the digits equals the original number. Examples Input: 121Output: YesExplanation: The number 121 remains the same when its digits are reversed. Input: 123Output: NoExp
      4 min read

    • C Program to Check for Palindrome String
      A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program. The simplest method to check for palindrome string is to reverse the given string and store it in a tem
      4 min read

    • C++ Program to Check if a Given String is Palindrome or Not
      A string is said to be palindrome if the reverse of the string is the same as the original string. In this article, we will check whether the given string is palindrome or not in C++. Examples Input: str = "ABCDCBA"Output: "ABCDCBA" is palindromeExplanation: Reverse of the string str is "ABCDCBA". S
      4 min read

    • Java Program to Check Whether a String is a Palindrome
      A string in Java can be called a palindrome if we read it from forward or backward, it appears the same or in other words, we can say if we reverse a string and it is identical to the original string for example we have a string s = "jahaj " and when we reverse it s = "jahaj"(reversed) so they look
      8 min read

    Easy Problems on Palindrome

    • Sentence Palindrome
      Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
      9 min read
    • Check if actual binary representation of a number is palindrome
      Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0’s are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
      6 min read
    • Print longest palindrome word in a sentence
      Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
      14 min read
    • Count palindrome words in a sentence
      Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
      5 min read
    • Check if characters of a given string can be rearranged to form a palindrome
      Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
      14 min read
    • Lexicographically first palindromic string
      Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
      13 min read
    geeksforgeeks-footer-logo
    Corporate & Communications Address:
    A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
    Registered Address:
    K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
    GFG App on Play Store GFG App on App Store
    Advertise with us
    • Company
    • About Us
    • Legal
    • Privacy Policy
    • In Media
    • Contact Us
    • Advertise with us
    • GFG Corporate Solution
    • Placement Training Program
    • Languages
    • Python
    • Java
    • C++
    • PHP
    • GoLang
    • SQL
    • R Language
    • Android Tutorial
    • Tutorials Archive
    • DSA
    • Data Structures
    • Algorithms
    • DSA for Beginners
    • Basic DSA Problems
    • DSA Roadmap
    • Top 100 DSA Interview Problems
    • DSA Roadmap by Sandeep Jain
    • All Cheat Sheets
    • Data Science & ML
    • Data Science With Python
    • Data Science For Beginner
    • Machine Learning
    • ML Maths
    • Data Visualisation
    • Pandas
    • NumPy
    • NLP
    • Deep Learning
    • Web Technologies
    • HTML
    • CSS
    • JavaScript
    • TypeScript
    • ReactJS
    • NextJS
    • Bootstrap
    • Web Design
    • Python Tutorial
    • Python Programming Examples
    • Python Projects
    • Python Tkinter
    • Python Web Scraping
    • OpenCV Tutorial
    • Python Interview Question
    • Django
    • Computer Science
    • Operating Systems
    • Computer Network
    • Database Management System
    • Software Engineering
    • Digital Logic Design
    • Engineering Maths
    • Software Development
    • Software Testing
    • DevOps
    • Git
    • Linux
    • AWS
    • Docker
    • Kubernetes
    • Azure
    • GCP
    • DevOps Roadmap
    • System Design
    • High Level Design
    • Low Level Design
    • UML Diagrams
    • Interview Guide
    • Design Patterns
    • OOAD
    • System Design Bootcamp
    • Interview Questions
    • Inteview Preparation
    • Competitive Programming
    • Top DS or Algo for CP
    • Company-Wise Recruitment Process
    • Company-Wise Preparation
    • Aptitude Preparation
    • Puzzles
    • School Subjects
    • Mathematics
    • Physics
    • Chemistry
    • Biology
    • Social Science
    • English Grammar
    • Commerce
    • World GK
    • GeeksforGeeks Videos
    • DSA
    • Python
    • Java
    • C++
    • Web Development
    • Data Science
    • CS Subjects
    @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
    Lightbox
    Improvement
    Suggest Changes
    Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
    geeksforgeeks-suggest-icon
    Create Improvement
    Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
    geeksforgeeks-improvement-icon
    Suggest Changes
    min 4 words, max Words Limit:1000

    Thank You!

    Your suggestions are valuable to us.

    What kind of Experience do you want to share?

    Interview Experiences
    Admission Experiences
    Career Journeys
    Work Experiences
    Campus Experiences
    Competitive Exam Experiences