Java Program to Check if a String is Palindrome - The Coding Shala

Home >> Java Programs >> Palindrome String Program

 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


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala