- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to check string as palindrome
A string is Palindrome if position of each character remain same in case even string is reversed.For example 'MADAM' is a palidrome string as position of each character remain same even if string 'MADAM' is reversed.Now in order to identify a string as palindrome or not we can use library method approach and also without library method approach.
But if we want to check if "Madam" is palindrome or not , it will show us that it is not a palindrome because of the upper case of first letter.
Example - Without library method.
public class Palindrome { public static void main(String[] args) { String str = "SATYA"; StringBuffer newStr =new StringBuffer(); for(int i = str.length()-1; i >= 0 ; i--) { newStr = newStr.append(str.charAt(i)); } if(str.equalsIgnoreCase(newStr.toString())) { System.out.println("String is palindrome"); } else { System.out.println("String is not palindrome"); } } }
Output
String is not palindrome
Example - With library method.
public class Palindrome { public static void main (String[] args) throws java.lang.Exception { String str = "NITIN"; String reverse = new StringBuffer(str).reverse().toString(); if (str.equals(reverse)) System.out.println("String is palindrome"); else System.out.println("String is not palindrome"); } }
Output
String is palindrome
Advertisements