string palindrome in java

In this article, we are going to discuss about palindrome string and write a code in java to check whether a given string is palindrome or not.

Palindrome String:-

A palindrome string is a string that remains the same after reversing the string for example-“abc”, this is not a palindrome string because after reversing the string it becomes “cba” which does not equal its original value. while string “abba” is a palindrome of string because after reversing the string it remains the same.

Steps to check palindrome string:-

  • Take a string input from user using scanner.
  • reverse the string and store in a new variable.
  • compare the original string and reverse string.
  • if both are the same then the string is a palindrome string.
  • else the given string is not a palindrome.

java code to check palindrome string without using inbuilt function:-

package gangforcode;
import java.util.*;
public class reverseString {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the string");
		String str=sc.next();
		String reverse="";
		for(int i=str.length()-1;i>=0;i--) {
			reverse=reverse+ str.charAt(i);
			}
		if(str.equals(reverse)) {
			System.out.println("string is palindrome");
		}
		else {
			System.out.println("string is not palindrome");
		}
	}}

Output:-

palindrome string in java

You can use the same logic to check whether the string is palindrome or not in other programming languages like C, C++, python, etc.

Leave a Comment