Palindrome Java

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn palindrome java.

Palindrome Java

Palindrome Java: Definition of palindrome

Palindrome string is a string where string remains same when reversed or a word that is spelled the same way forwards and backwards.

For example the word level, dad, mom, madam, abcba, etc.,

So the way we are going to write a java program with some of the string methods to test if a word is a palindrome, we are going to start off by storing our palindrome in a string variable like,

String str = "level";

Next we are going to define the start position of the string which will be used in our substring method later on.

We are going to do our start position of a string which is 0. Because strings start at zero

int startPosition = 0;

And our end position is going to be the length of the string. This is another method from the string class which will return the length of our string.

Here we have to do minus 1 to indicate the last character in the string.

int endPosition = str.length() - 1;

Now we also need a boolean variable to indicate whether our word is a palindrome or not

boolean checkPalindrome = true;

And now we can start our main while loop which will continue as long as our start position is less than our end position.

Because the way we are going to implement this loop where we are going to compare the first letter to the last letter and continue there onwards.

Also Read – Palindrome number in java

So what I mean by that is, we are going to move our start position by 1 and decrement our end position by 1 with every single iteration of the loop.

In that way they meet in the center. But in order to properly test that our word is palindrome we are going to have to create a little substring variables that will test whether the two letters are actually equal.

So first we are going to create a string variable called “startLetter” which will hold our start letter which will be a substring of the initial palindrome variable substring which will start at the start position and will end at the start position plus 1.

Same thing goes for variable “endLetter”. It will be a substring of the “str” variable and it will start at the end position and end at the end position plus 1.

So that way since our end position is currently pointing to the last character our substring method will know to get the character that is starting at the last position all the way to the end of the string.

Therefore during the first iteration we will get the letter “l” which is the last letter and during our start letter we also start with letter “l” in this case.

So all we have to do is to actually compare if they are equal by using the equals method dot equals the end letter.

But in this case what we are going to do is test if the equals method returns false.

If it does, we are going to break out of the loop and indicate that this word is not a palindrome by setting out “checkPalindrome” variable equal to false.

Here’s the while loop code for the above explanation,

while(startPosition < endPosition)
{
   String startLetter = str.substring(startPosition, startPosition + 1);
   String endLetter = str.substring(endPosition, endPosition + 1);

   if(startLetter.equals(endLetter) == false)
   {
      checkPalindrome = false;
      break;
   }
   startPosition++;
   endPosition--;
}

In the end we are going to check out “checkPalindrome” variable equal to true. If it is true we know that our variable is palindrome.

Else we know that the variable must have been turned to false. Therefore it must be “must not be a palindrome”.

Here’s the complete code for palindrome in java,

public class PalindromeInJava 
{
   public static void main(String[] args) 
   {
      String str = "level";
      int startPosition = 0;
      int endPosition = str.length() - 1;
      boolean checkPalindrome = true;
 
      while(startPosition < endPosition)
      {
         String startLetter = str.substring(startPosition, startPosition + 1);
         String endLetter = str.substring(endPosition, endPosition + 1);

         if(startLetter.equals(endLetter) == false)
         {
            checkPalindrome = false;
            break;
         }
         startPosition++;
         endPosition--;
      }
 
      if(checkPalindrome == true)
      {
         System.out.println(str + " is a palindrome.");
      }
      else
      {
         System.out.println(str + " is not a palindrome.");
      }
   }
}

Output:

level is a palindrome.


Note

There’s one more interesting case. What if we just capitalize one letter (in the above program change variable String str = “Level”)? Logically we know that this word is palindrome.

But does our program know that? Unfortunately it’s not !!! It’s not a palindrome.

What we need to do is we need to use another string method called “toLowerCase()”, like this

String strOriginal = "Level";
String str = strOriginal.toLowerCase();

There’s also another way to check whether our word is a palindrome without using substring method of the string class.

What we could do is assign the variable to a “char” variable using the chatAt() method at start position and we can also create another “char” variable for the end letter using the same logic.

char startLetter = str.charAt(startPosition);
char endLetter = str.charAt(endPosition);

Also we have to change the “if” condition to this,

if(startLetter != endLetter)

Here’s the complete code for palindrome program in java,

public class PalindromeInJava 
{
   public static void main(String[] args) 
   {
      String strOriginal = "Level";
      String str = strOriginal.toLowerCase();
      int startPosition = 0;
      int endPosition = str.length() - 1;
      boolean checkPalindrome = true;
 
      while(startPosition < endPosition)
      {
         char startLetter = str.charAt(startPosition);
         char endLetter = str.charAt(endPosition);

         if(startLetter != endLetter)
         {
            checkPalindrome = false;
            break;
         }
         startPosition++;
         endPosition--;
      }
 
      if(checkPalindrome == true)
      {
         System.out.println(strOriginal + " is a palindrome.");
      }
      else
      {
         System.out.println(strOriginal + " is not a palindrome.");
      }
   }
}

Output:

Level is a palindrome.


Example: java palindrome using for loop

Let’s learn java palindrome using for loop,

import java.util.*;

public class PalindromeStringInJava
{
   public static void main(String[] args)
   {
      String original;
      String reverse = "";

      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string to check : ");
      original = sc.nextLine();
      int number = original.length();

      for(int a = number - 1; a >= 0; a--)
      {
         reverse = reverse + original.charAt(a);
      }
      if(original.equals(reverse))
      {
         System.out.println(original + " is a Palindrome string.");
      else
      {
         System.out.println(original + " is not a Palindrome string.");
      }
   }
}

Output:

Palindrome Java


Palindrome java program without reversing a string

Now we will learn simple palindrome program in java for string without reversing a string,

import java.util.Scanner;

public class PalindromeString 
{
   public static void main(String[] args) 
   { 
      Scanner sc = new Scanner(System.in);
 
      System.out.println("Input a string to check if string is palindrome : ");
      String strString = sc.nextLine();
 
      int length = strString.length();
      int a, begin, end, middle;
 
      begin = 0;
      end = length - 1;
      middle = (begin + end) / 2;
 
      for(a = begin; a <= middle; a++) 
      {
         if(strString.charAt(begin) == strString.charAt(end)) 
         {
            begin++;
            end--;
         }
         else
         {
            break;
         }
      }
      if(a == middle + 1) 
      {
         System.out.println(strString + " is palindrome string in java.");
      }
      else
      {
         System.out.println(strString + " is not a palindrome string in java.");
      }
      sc.close();
   }
}

Output:

Input a string to check if string is palindrome : madam
madam is palindrome string in java.


Palindrome Java: java palindrome using library methods

Let us learn palindrome in java or check if a string is a palindrome java using library methods,

public class JavaPalindrome 
{
   public static void isPalindrome(String str)
   {
      String strReverse = new StringBuffer(str).reverse().toString();
 
      // checking for string is palindrome or not in java
      if(str.equals(strReverse))
      {
         System.out.println(str + " is palindrome string in java.");
      }
      else
      {
         System.out.println(str + " is not a palindrome string in java.");
      }
   }
 
   public static void main(String[] args)
   {
      isPalindrome("eye");
      isPalindrome("rotator");
   }
}

Output:

eye is palindrome string in java.
rotator is palindrome string in java.


Recursive palindrome java

So here let us learn recursive palindrome or palindrome recursion java to check if a string is a palindrome,

public class RecursivePalindromeJava 
{
   // check if a string is a palindrome
   static boolean palindromeRecursion(String str, int a, int b)
   {
      // check if there is one character
      if(a == b)
         return true;
 
      // checking if first and last character does not match
      if((str.charAt(a)) != (str.charAt(b)))
         return false;
 
      // checking whether if middle substring is palindrome
      if(a < b + 1)
         return palindromeRecursion(str, a + 1, b - 1);
 
      return true;
   }
 
   static boolean isPalindromeJava(String str)
   {
      int x = str.length();
      // Here empty string is considered as palindrome 
      if(x == 0)
         return true;
 
      return palindromeRecursion(str, 0, x - 1);
   }
 
   public static void main(String[] args) 
   {
      String str = "rotator";
 
      if(isPalindromeJava(str))
      {
         System.out.println(str + " is palindrome string in java.");
      }
      else
      {
         System.out.println(str + " is not a palindrome string in java.");
      }
   }
}

Output:

rotator is palindrome string in java.


conclusion

That’s it guys. This was all about palindrome string in java, what is palindrome string, recursive palindrome java and how to check if a string is a palindrome in java using recursion.

I hope you guys have understood the concept. You can subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like.

You May Also Like