Frequently Asked Java Program 02: Java Program to Check if Any String is Palindrome Without Using Reverse Method
Hello Folks,
As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a Java program to verify if a given string is palindrome without using inbuilt reverse method.
WHAT IS A PALINDROME STRING?
A palindromic string is a string that remains the same when its characters are reversed.
For Example: NAAN, AMMA AMMA etc.
Logic:
Since we can not use built in reverse method, so we will use different logic.
- We will convert given string in to char array first.
- Read char from char array from last index and concatenate.
Java Program:
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 32 33 34 35 36 37 |
package StringPrograms; import java.util.Scanner; public class PalindromeCharString { public static void main(String[] args) { // Reading string from user input Scanner sc = new Scanner(System.in); System.out.println("Please enter the string to check palindrome:"); String inputByUser = sc.nextLine(); // Closing input scanner sc.close(); // converting string in to char array char[] stringInChar = inputByUser.toCharArray(); // Declaring an empty string variable to store reverse string String reverseInput = ""; // reading char by char from end of array till first and forming a string for (int i = stringInChar.length - 1; i <= 0; i--) { reverseInput = reverseInput + stringInChar[i]; } // Printing both actual and reversed string System.out.println("Inout string:" + inputByUser); System.out.println("Reverse String:" + reverseInput); // Checking if given string is plaindrome if (inputByUser.equals(reverseInput)) System.out.println("Entered string is palindrome."); else System.out.println("Entered string is not palindrome."); } } |
Output: Please enter the string to check palindrome: NANA Inout string:NANA Reverse String:ANAN Entered string is not palindrome. =============================================================== Please enter the string to check palindrome: AMMA Inout string:AMMA Reverse String:AMMA Entered string is palindrome.
You can run above program for multiple inputs and if it fails for any condition, let me know.
#HappyCoding
Author: Amod Mahajan
A software Tester who is paid to judge products developed by others. Writing technical posts and creating YouTube videos are my hobbies.