Java Program to Check if a String is Palindrome - The Coding Shala
Home >> Java Programs >> Palindrome String Program
Other Posts You May Like
In this post, we will learn how to Check whether a given String is Palindrome or Not in Java.
Java Program to Check if a String is Palindrome
Write a Java Program to Check if the given string is a palindrome string or not. A palindrome string is a string that is the same after reverse also. For example, the "abba" string is a palindrome string.
Example 1:
Input: helleh
Output: Palindrome String
Example 2:
Input: Akshay
Output: Not a Palindrome String
Approach
First, we can find the reverse string then compare it with the original string to check palindrome.
We can also check palindrome without finding the reverse string. Just compare the characters from the start and from the end, those are at the same distance. If all the characters at i distance are not the same as (length - i) distance then it's not a Palindrome string.
Java Program:
// Java program to Check Palindrome String import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a String: "); String str = sc.nextLine(); boolean isPalindrome = true; for (int i = 0; i < str.length() / 2; i++) { // check char from starting and from end at the same distance if(str.charAt(i) != str.charAt(str.length()-i-1)) { isPalindrome = false; break; } } if (isPalindrome) { System.out.println("Given string is a Palindrome string"); } else { System.out.println("Given string is not a Palindrome string"); } sc.close(); } }
Output:
Enter a String:
helleh
Given string is a Palindrome string
- Java Program to Check if a Number is Palindrome
- Java Program to Reverse a Number
- Java Program to Check Prime Number
- Java Program to Reverse a String
- Java Program to Count Number of Vowels in a String
Comments
Post a Comment