Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Palindrome Program in Java | Java Program To Check Polindrome

Updated on 25 November, 2022

6.01K+ views
7 min read

Introduction

Java has gained a lot of limelight among programmers because of its simplicity, architecture neutrality, platform independence, distributed execution, and reusability. Also, java has many predefined libraries for seamless programming. And everyone will be enthusiastic to code in such a language.

Now coming to our topic, we are going to write a java code to check if the given input is a palindrome or not.

A number or word is said to be a palindrome if it remains the same after reversing it. And we can implement a solution iteratively as well as recursively. So let’s get started!

Check out our free courses to get an edge over the competition

Iterative Java Code

The idea is simple; we’ll declare a variable ‘reverse’ which stores the reversed number of our input.

We will multiply the reverse variable by 10(to fill the unit’s position with 0) in every iteration. Then, we will add the remainder of the input number after dividing it by 10. After adding the rest, we will divide the input number by 10 (to remove the number in the unit’s position).

We’ll stop the above algorithm when the input number becomes 0, and the number present in the reverse variable will be the reverse of the input number.

Check out upGrad’s Advanced Certification in Cloud Computing 

public class upGrad{
public static void main(String[] args) {
int n=12221;
int reverse=0;
int temp=n;
while(temp>0){
reverse=reverse*10;
reverse=reverse+temp%10;
temp=temp/10;
}
if(reverse==n)
System.out.print(n+” is a palindrome”);
else
System.out.print(n+” is not a palindrome”);
}
}

In the above code, we’ve declared a variable ‘n’ which stores the initial number, and we’ve to check if the number n is a palindrome or not. In the while loop, we’ll follow the algorithm which we’ve discussed earlier. And finally, we are checking if the reversed number is equal to the initial number or not. If the changed number and the initial numbers are similar, we are printing it as a palindrome else, not a palindrome.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Now, this code will work only for an integer input. And if we want to check if a given word is a palindrome or not, we’ve to deal with it using strings. And here’s the code to do that.

Check out upGrad’s Advanced Certification in Cyber Security

public class upGrad{

public static void main(String[] args) {

String s=”rotor”;

String reverse=new String();

for(int i=s.length()-1;i>=0;i–)

reverse=reverse+s.charAt(i);

if(s.equals(reverse))

System.out.print(s+” is a palindrome”);

else

System.out.print(s+” is not a palindrome”);

}

}

In the above code, we are appending the initial string’s characters from the tail to the head to the reverse string and checking if it is equal to the initial string or not. We have hardcoded the string with a word, but we can initialize it with user input using the scanner class.

Recursive Java Code

In this implementation, we are going to compare the first and last characters. And if they are equal, then recur further for the remaining string.

But this logic will not work for the strings which have an odd number of characters. So if we include a base case, where we conclude a string as a palindrome, if the length of a string is one, i.e., the first and last characters’ position is the same. This would clear our issue with odd-sized strings because we’ll recur to the middle element and then conclude it as a palindrome since only a single character remains in the middle.

public class upGrad{

    public static boolean isPalindrome(String str, int low, int high){

        if(low==high)

            return true;

        if(str.charAt(low)!=str.charAt(high))

            return false;

        if(high-low>1)

            return isPalindrome(str,low+1,high-1);

        return true;

    }

public static void main(String[] args) {

String s1=”rotor”;

String s2=”programming”;

System.out.println(isPalindrome(s1,0,s1.length()-1));

System.out.println(isPalindrome(s2,0,s2.length()-1));

}

}

In the above code, we have written a function that expects a string, two integers as the parameters. And the two integers, low, high are the pointers that keep track of the characters which have to be checked. And if the names at the position low and high are equal.

we’ll call the same function with updated parameters such that the string is shrunk from both sides by one character. And if the pointers low and high meet each other or a single character is present between them, then we’ve reached till the middle of the string and concluding it as a palindrome.

Now, let’s have a dry run of the code for the string “rotor”. Initially, the low is 0, and the high is 4. Since the character at 0th position (‘r’) is equal to the character at 4th position (‘r’), we’ll make a recursive call with low updated as low+1 and high updated as high-1.

Now, low is 1, and high is 3 since characters at those positions are equal, we’ll again make a recursive call. Now low is 2 and high is 2, and it triggers the base case where low is equivalent to high, so we’ll return true.

We can also implement a recursive function to check if an integer is a palindrome or not, and here’s the process to do that.

static boolean isPalindrome(int n, int rev, int temp){

        if(temp==0)

            return n==rev;

        rev=rev*10;

        return isPalindrome(n,rev+temp%10,temp/10);

    }

Note that, in the above function, initially n and temp are the same. Because at last, we’ve to compare the reverse number with the initial number, so all the computations are performed on the same variable. The initial number should not be altered.

Also Read: Java Project Ideas & Topics

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusion

We’ve understood the definition of palindrome, walked through iterative and recursive codes for checking if a string/number is a palindrome or not. We know the code by a dry run of sample example. Now that you are aware of implementing a code to check palindrome try implementing it using the scanner class and try coding it using OOP concepts.

If you wish to improve your Java skills, you need to get your hands on these java projects. If you’re interested to learn more about Java, full-stack development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development, which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. What is a palindrome?

Palindromic sentence is a literary composition, phrase, verse, or word, reading the same backward or forward. A palindrome is a type of word play, specifically a word or phrase (sentence) which reads the same backward or forwards. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. For example, A man, a plan, a canal, Panama! is a palindrome. Some palindromes are not words, such as the number 106601. Some palindromes are phrases, such as Madam, I'm Adam.

2. How to prepare for a Java interview?

If you want to be a Java expert, you need to make sure a few things are in order first. First and foremost, you need to have a good working knowledge of the Java language. Secondly, you should have a good understanding of the Java API. You don't have to have an absolute mastery of the API, but you should have an understanding of what's available and when to use which class. Finally, you need to have a deep understanding of the Java Virtual Machine. For example, you should be able to write an interpreter for a simple language. If you're interviewing for a compiler development position, you're off the hook.

3. How to write good Java programs?

Some of the best practices while writing the program in java are: Always use 'public class' to start the class. Never use 'public static void main' inside a class. Never use 'this' keyword inside the class. Never use 'final' modifier on methods. Never use the 'static' modifier on the instance variables. Never make variables 'public' unless it is absolutely necessary. Always have a good naming convention. Never make a variable more than one letter with a numeric suffix. Avoid making variables with more than one word. Never use 'this' keyword inside the method. Never use 'break' keyword.

RELATED PROGRAMS