Java Program to Check String Palindrome

What is String Palindrome

Suppose String s1= MADAM
        String s2=reverse(s1)//reverse
        if s1==s2
        then it a palindrome string  
        else it is not a palindrome String
Note: this is not a exact logic its just for understanding.

In this Topic we are going to take two examples.In Example-1 we will take Static Inputs(pre-defined Inputs). And in Example-2 we will take User Defined Inputs.

Algorithm/Program Explanation

  1. Start
  2. Take String s=”MADAM” as input
  3. StringBuffer revstr= new StringBuffer()// reverse string is stored here.
  4. Define For Loop
    • for(int i=s.length()-1;i>=0;i–)
    • revstr=revstr.append(s.charAt(i))
  5. Check for Condition
    • if(s.equalsIgnoreCase(revstr.toString()))
    • Print String is Palindrome
    • else String is not a Palindrome
  6. End

Example-Taking Static Inputs

/*
Java Program to Check String Palindrome */
public class PalindromeString {
    public static void main(String args[]){
        String s="MADAM";
        StringBuffer revstr= new StringBuffer();
        for(int i=s.length()-1;i>=0;i--){
            revstr=revstr.append(s.charAt(i));
        }
        if(s.equalsIgnoreCase(revstr.toString())){
            System.out.println("String is Palindrome");
        }
        else{
            System.out.println("String is not a Palindrome");
        }

    }
}

Output:
String is Palindrome

Example-2 Taking User Defined Inputs

/* 
Java Program to Check String Palindrom */
import java.util.Scanner;

public class PalindromeString {
    public static void main(String args[]){
        System.out.println("Enter the String");
        Scanner sc=new Scanner(System.in);
        String s=sc.next();
        StringBuffer revstr= new StringBuffer();
        for(int i=s.length()-1;i>=0;i--){
            revstr=revstr.append(s.charAt(i));
        }
        if(s.equalsIgnoreCase(revstr.toString())){
            System.out.println("String is Palindrome");
        }
        else{
            System.out.println("String is not a Palindrome");
        }

    }
}

Output:
Enter the String
dad
String is Palindrome

Related Topics

Leave a Comment