Java program to check for palindrome


Hey guys, welcome back to this new post where we will learn how to write a java program to identify a palindromic sequence. This is one of the most commonly asked interview questions in Java coding interviews.




Palindrome is nothing but a sequence of characters that is equal to the set of characters obtained by reversing the string. 

For. e.g. if there is a string called "NITIN". If we reverse this string, the resulting string will be "NITIN". Here both the original string and the reversed string of characters are the same. Hence this is an example of a palindromic sequence of characters.


Let us try to write a Java program to identify if a given string is palindrome or not:

We can do it via 2 approaches. 

  1. Java program by iterating the string and then comparing the reversed string
  2. Java program by reversing the string via inbuilt Java StringBuilder API and then comparing the reversed string.


Approach 1:

package test;

public class Palindrome2 {

public static void main(String[] args) {

// Java program to check string for palindrome

String origStr = "nitin";


String revStr = "";

for (int i = 0; i < origStr.length(); i++) {

revStr = revStr + origStr.charAt(origStr.length() - i - 1);

}


if (origStr.equalsIgnoreCase(revStr)) {

System.out.println("Palindrome");

} else {

System.out.println("Not Palindrone");

}

}

}




Approach 2:

package test;

public class Palindrome {

public static void main(String[] args) {

// Java program to check string for palindrome

String origStr = "aaloyolaA";

StringBuilder strB = new StringBuilder(origStr);

String revStr = strB.reverse().toString();


if (origStr.equalsIgnoreCase(revStr)) {

System.out.println("Palindrone");

} else {

System.out.println("Not palindrome");

}

}

}


Hope these 2 program helps you understand the approach to solve this question. Happy programming.

Follow Me on Social Media

Advertisement
FREE Sales CRM Software

Fully customizable CRM Software for Freelancers and Small Businesses

Signup for Free

Sign up for DigitalOcean Cloud

Get FREE $200 credits, deploy your hobby projects for Free

DigitalOcean Referral Badge
Sign up for Hostinger Cloud or VPS plans and get upto 20% Discount