Palindrome: A string is said to be in a Palindrome if it remains the same when its elements are reversed or are the same as forward.
For example: 14141, 777, 272 are palindrome numbers as they remain the same even if reversed. If we take the example of ‘mam’ or ‘madam’, these are also palindrome words.
Java program to check String is palindrome or not
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | //check for the string Palindrome import java.util.Scanner; public class StringPalindrome { public static void main(String args[]) { String str1, str2= ""; Scanner sc = new Scanner(System.in); System.out.print("Enter the String: "); str1 = sc.nextLine(); for(int i = str1.length() - 1; i >= 0; i--) { str2 += str1.charAt(i); } //equalsIgnoreCase = This method returns true if the argument is not null and //it represents an equivalent String ignoring case, else false if(str1.equalsIgnoreCase(str2)) { System.out.println("The entered string is palindrome."); } else { System.out.println("The entered string is not palindrome."); } } } |
Output:
Enter the String: Madam
The entered string is palindrome.
Using StringBuilder’s reverse() function:
Java program to check String is palindrome or not using the StringBuilder reverse() function. This function takes the string and reversed it or takes each of the elements from backward.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the sstring to be check : "); String str = scanner.nextLine(); StringBuilder strBdr = new StringBuilder(str); //reversing strBdr.reverse(); //Display if(str.equals(strBdr.toString())) { System.out.println("Entered String is palindrome"); } else { System.out.println("Entered String is not palindrome"); } } } |
Output:
Enter the sstring to be check : Madam
Entered String is palindrome