Write a java program to checks whether a given string is a palindrome or not

Java program to checks whether a given string is a palindrome or not

In this program, we learn to chacks whether a given string is a palindrome or not.

Algorithm: Palindrome or not in Java

  1. import java.util.*;
  2. Create: class Palind{
  3. Create main function: public static void main(String args[]){
  4. String original, reverse=””;
  5. Scanner in = new Scanner(System.in);
  6. Print message “Enter a string to check if it is a palindrome”
  7. Read string: original = in.nextLine();
  8. Find length: int length = original.length();
  9. for ( int i = length – 1 ; i >= 0 ; i– )
    1. reverse = reverse + original.charAt(i);
  10. if (original.equals(reverse)) {

  11. System.out.println(“Entered string is a palindrome.”);

  12. else:  System.out.println(“Entered string is not a palindrome.”);

Source Code: Palindrome or not

import java.util.*;

class Palind
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);

System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();

int length = original.length();

for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);

if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");

}
}

Expected Output:

 
Enter a string to check if it is a palindrome
Madam
Entered string is a palindrome
 
Write a java program to Checks whether a given string is a palindrome or not

FAQ:

How do you reverse a string in Java?

To reverse a string: for (int i = length – 1; i >= 0; i–)
reverse = reverse + original.charAt(i);

How do you check if a given string is a palindrome Java?

To check a given string is a palindrome in java, we have to compare reverse with real string.
if (original.equals(reverse))

Recommended Post:

Find the solution to the salesforce Question and many more

Tags: palindrome or not in java, palindrome or not

Leave a Reply

%d bloggers like this: