Java Program to Check if String is Palindrome or not

Palindrome check program in Java

preview

Hello! Let's learn to make a java program to check if the given string is Palindrome or not.

What is a Palindrome ?
A String is called a Palindrome when the reverse of that string is same as the original string. For example - racecar, nitin, etc.

Please follow the below code and get started 💻.

Java Code

public class Main
{
  /* function to check if string is Palindrome or not */
  static void checkPalindrome(String str) {
    boolean res = true;
    int len = str.length();
    
    for(int i=0; i<=len/2; i++) {
      if(str.charAt(i) != str.charAt(len-i-1)) {
        res = false;
          break;
      }
    }
    
    // print the output
    if(res) 
      System.out.println(str + " is a Palindrome");
    else 
      System.out.println(str + " is not a Palindrome");
  }
    
  public static void main(String[] args) {
    String str = "racecar";  // string to check Palindrome
    
    // convert string to lowercase
    str = str.toLowerCase();
	checkPalindrome(str);
  }
}


Output

racecar is a Palindrome

That is all! I hope you find this helpful. Thanks for visiting my blog.
Post a Comment (0)
Previous Post Next Post