Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is String Palindrome Program in Java?
3.
Example of String Palindrome in Java
4.
Methods to Check String Palindrome in Java
4.1.
1. Naive Approach
4.2.
Java
4.3.
2. Recursive approach
4.4.
Java
4.5.
3. Two Pointer Method
4.6.
Java
5.
Complexities of String Palindrome in Java
5.1.
Time Complexity
5.2.
Space Complexity
6.
Frequently Asked Questions
6.1.
What is String palindrome in Java?
6.2.
How do you make a string palindrome?
6.3.
What is palindrome string logic?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Java Program to Check if a String is Palindrome

Author Saksham Gupta
0 upvote

Introduction

You just can't go to a technical interview without preparing the hot topic, i.e., Strings. Interviews after the interview, we see questions about strings being asked. Thus it's important to master such a topic. So to help you, your Ninja is here, and today, we will see Java Program to Check if a String is Palindrome or not.

string palindrome in java

What is String Palindrome Program in Java?

Before solving the problem ‘string palindrome in java’ we should know that if a string is the same when read from left to right or right to left, it is said to be a palindrome. So, let's take the string "str," and the task now is to determine whether its reverse string is the same as it is.

Palindrome problems in Java typically necessitate efficient string reversal methods, character comparison, and loop constructions. Using Java's built-in libraries or implementing customized algorithms are standard techniques for effectively addressing such difficulties. Understanding data structures such as stacks or queues can also help you improve your palindrome-solving abilities.

Let's understand the problem ‘string palindrome in java’ by the following example.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example of String Palindrome in Java

Input

‘S’ = ‘abba’

Output

YES

Explanation:

We can see that the string is the same from left to right and right to left. 

abba = abba,

So it is a string palindrome in java.

Now, Let's learn to write a string palindrome program in java.

Methods to Check String Palindrome in Java

In this section, we will discuss how we can actually find if the given string is palindrome or not. There are mainly two methods to check string palindrome in Java; here are the following methods:

1. Naive Approach

This will be our first and basic approach to checking the palindrome string. We know if the given string (on which we have to check for palindrome) and its reverse are equal, then we can say the string is a palindrome; otherwise, not. So we will be doing this process in this approach; here are some of the steps to understand this approach:

Step 1: First, we have to initialize the given string and its reversed string with “” because we will store the reverse of the given string to this.

Step 2: We will iterate through the given string from end to start so that we can have the reverse of this string, and while iterating, we will store each character in the extra created string.

Step 3: Now we have the given string and its reversed string, we can now compare both of them. While comparing, we also have to convert them to lowercase, and If they are the same, then the given string is palindrome or else not.

Here's the implementation of Java code for this naive approach:

  • Java

Java

class Main {
public static void main(String[] args) {

// Here are two strings 's' is the string for which we have to check for palindrome.
// 'rev_s' will be the reverse of 's', initialized with "" right now.
String s = "Ninja", rev_s = "";

// 'n' is the length of s.
int n = s.length();

// Looping through the 's' from end to start and storing each character to 'rev_s', so that 'rev_s' will store the reverse of 's'.
for(int i = n - 1; i >= 0; i--)
rev_s += s.charAt(i);

// Now for comparing, we have to compare both the strings to lowercase and then compare them, If they are equal then 's' is palindrome Else not.
if(s.toLowerCase().equals(rev_s.toLowerCase()))
System.out.println(s + " is a Palindrome String.");
else
System.out.println(s + " is not a Palindrome String.");
}
}

 

The output of the above implementation:

Ninja is not a Palindrome String.

2. Recursive approach

This will be our second recursive approach, where we will not use any extra memory or space. As we used a reversed string of the given string for comparison, but here we will not use any extra space. Instead, we will use recursion to solve our problem. The intuition of the approach is to compare the first and the last index character at a time, If we continue this for every character; the problem will be solved. Here are the steps that we will be going to use in this approach:

Step 1: First, we will initialize the given string with any value. let's just say “Ninjas”.

Step 2: Now, we will call the recursive function that returns the boolean value (True or False). If the function returns true, the given string is a palindrome; otherwise, not.

Step 3: Now, what we have to do is iterate the string with start + 1 and end - 1 as we are comparing the start and the end index character.

Step 4: If anytime start gets equal to the end (base condition), means the given string is palindrome, and there are no more characters for comparison.

Step 5: If the character at the start and end are equal, we can continue the process till the base condition meets. Else if the characters are not equal, we don't have to continue the process, and we can return false.

Here's the implementation of Java code for this recursive approach:

  • Java

Java

public class Main {
public static boolean isPalindrome(String s, int start, int end) {

// First we will check if the 'start' is equal to 'end';
// Means there are no more characters to check and its a palindrome strins. So return true.
if (start == end)
return true;

// Checking if the characters are equal, so we will move to next step.
// To move to a next step, we have increment 'start' and decrement 'end'.
if (s.charAt(start) == s.charAt(end))
return isPalindrome(s, start + 1, end - 1);

// If the characters are not equal, No need to move just return false.
return false;
}
public static void main(String[] args) {

// Initialize givens string 's' with any value.
String s = "Ninjas";

// 'n' is the length of 's' string.
int n = s.length();

// If the recursive function 'isPalindrome' return true, means the string is palindrome. else not.
if(isPalindrome(s.toLowerCase(), 0, n - 1))
System.out.println(s + " is a palindrome.");
else
System.out.println(s + " is not a palindrome.");
}
}

 

The output of the above implementation:

Ninjas is not a palindrome.

3. Two Pointer Method

This is the 3rd approach where we will see how efficiently we can find whether the string is palindrome or not using the two-pointer approach.

Step 1: The strategy will be to first transform the string to lowercase. 

Step 2: Take two pointers, 'i' pointing to the beginning of the string and 'j' pointing to the end.

Step 3: Continue to increment i and decrease j while i < j and check whether the characters at these addresses are the same or not at each step. If not, the string is not a palindrome; otherwise, it is.

Here's the implementation of Java code for this two pointer approach approach:

  • Java

Java


public class Ninja {


// Return true if string is palindrome
static boolean isPalindrome(String s)
{

// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = s.length() - 1;
while (i < j) {

if (s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}

return true;
}

public static void main(String[] args)
{
String s = "121nitin121";

// Convert the string to lowercase
s = s.toLowerCase();
if (isPalindrome(s))
// It is a palindrome
System.out.print(s+" "+"is palindrome");
else
// Not a palindrome
System.out.print(s+" "+"is not palindrome");
}
}

 

The output of the above implementation:

121nitin121 is palindrome

Complexities of String Palindrome in Java

Time Complexity

O(N), where ‘N’ is the length of the string

Reason: As we are looping over the entire string only once, it will cost us O(N) time to solve the problem ‘string palindrome in java’.

Space Complexity

O(1).

Reason: We are not using any extra variable space thus the space complexity would be O(1) for the problem ‘string palindrome in java’. 

Also read palindrome number in python.

Frequently Asked Questions

What is String palindrome in Java?

String palindrome is a very famous question that is frequently asked in various coding interviews. The problem is to determine and write code in Java to find whether a given string is a palindrome or not.

How do you make a string palindrome?

A palindrome string is a string that is the same when read from left to right or right to left. To make a string palindrome we have to make its left half equal to its right half. This can be done by concatenating the reverse of the original string to the original string. In this way, we can make a string palindrome.

What is palindrome string logic?

The logic of the problem palindrome string is that we need to find if a string is the same when read left to right and right to left. To check this we can use two pointers to iterate simultaneously from left to right and right to left and check it the corresponding characters are the same or not. If they are the same for all the indexes then the answer will be yes, else no.

Conclusion

We saw how we discussed the Java Program to Check if a String is Palindrome. and wrote a string palindrome program in java. Other problems involving strings and similar to the problem ‘string palindrome in java’ are Lexicographically largest String after removal of K charactersCount of Increasing Substrings in given String, String Interview Questions In Java, etc. 

Recommended Readings:

 

Now don't waste any more time and head over to our practice platform Coding Ninjas Studio to practice top problems on every topic, interview experiences, and many more.

Previous article
Printing Pattern in Java
Next article
Reverse a String in Java
Live masterclass