Get a string from user and check whether the string is palindrome or not a palindrome. Palindrome strings are madam, dad, malayalam, etc. These strings which when reversed read as the same. Hence, these are palindromic strings. While, coderegister, programming are not palindrome strings, since, when they reversed they are read as retsigeredoc, gnimmargorp.
Input 1:
madam
Output 1:
The String madam is a palindrome
Input 2:
coderegister
Output 2:
The String coderegister is not a palindrome
Java Implementation:
Using Built-in Java Methods:
Input 1:
madam
Output 1:
The String madam is a palindrome
Input 2:
coderegister
Output 2:
The String coderegister is not a palindrome
Java Implementation:
Using Built-in Java Methods:
import java.util.*; import java.lang.*; import java.io.*; class CodeRegister { public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); if(palindrome(str)) System.out.println("The String " + str + " is a palindrome"); else System.out.println("The String " + str + " is not a palindrome"); } static boolean palindrome(String s) { String v = new StringBuilder(s).reverse().toString(); return s.equals(v); } }
Using User-Defined Method:
import java.util.*; import java.lang.*; import java.io.*; class CodeRegister { public static void main (String[] args) throws java.lang.Exception { /* get the input string from user */ Scanner in = new Scanner(System.in); String str = in.next(); /* a boolean function isPalindrome(String) will return either true or false */ if(isPalindrome(str)) System.out.println("The String \""+ str +"\" is a palindrome"); else System.out.println("The String \""+ str +"\" is not a palindrome"); } /* function to check whether the input string is palindrome or not */ static boolean isPalindrome(String s) { /* convert the string to character array, since we want to deal with the characters of string */ char ch[] = s.toCharArray(); /* setting left index to 0 & right index to (length_of_string - 1)*/ int l = 0; int r = s.length()-1; /* Do until the left index is less than the right index */ while(l<r) { if(ch[l]!=ch[r]) { return false; // return false, if the character at left index and right index do not match } l++; // increment the left index r--; // decrement the right index } return true; // return true, if all the characters at left index and right index matches } }