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:
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.");
}
}
[java]
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.
[/java]
You can run above program for multiple inputs and if it fails for any condition, let me know.
#HappyCoding