Check if String is Palindrome in Java

Let us check if the string is a palindrome in Java. The idea is common, and the implementation is simple.These few lines will check the string is palindrome or not.







 import java.util.*;
class PalindromeString
{

    public static void main(String args[])
    {
  
    // Create a Scanner object
    Scanner s=new Scanner(System.in);

    System.out.println("Enter the string");

    // Read the data
    String st1=s.nextLine();

    // Create StringBuffer obj for st1
    StringBuffer sb=new StringBuffer(st1);

    // Reverse the letters
    sb.reverse();

        // Check & Print if palindrome
        if(st1.equals(sb.toString()))
        System.out.println("Palindrome String");

    }

}

Analysis

Create a StringBuffer object. For the st1because the reverse()method is in StringBuffer.
sb.reverse() Reverse the string associated with StringBuffer object.
st1.equals(sb.toString()) Convert StringBuffer object to String type for checking equality using equals() method.

Other way.. It is manually reversing the string by a simple logic without need of creating a StringBuffer object.

In this way, we can simply check if the given string is palindrome or not in Java. Comment.

No comments: