Palindrome Delete Replace Reverse Java Example


Palindrome – Practical Example

A word that reads the same from start to end and end to start is known as palindrome. Observe, the following palindrome program written in Java is how much simpler than that of C/C++.

public class PalindromeTest
{
   public static void main(String args[])
   {					
      String s1 =  "RADAR";
      StringBuffer buffer1 = new StringBuffer(s1);
      StringBuffer buffer2 = buffer1.reverse();
      System.out.println(buffer2);		        // RADAR

      String s2 = buffer2.toString();
      if(s1.equals(s2))
           System.out.println("Palindrome");		// Palindrome
      else
           System.out.println("Not palindrome");		
     }
}

Palindrome
Output screen of PalindromeTest.java

buffer1.reverse() statement reverses the characters in the original StringBuffer buffer1 itself.

String s2 = buffer2.toString();

The equals() method requires two string objects to compare. For this reason, buffer2 is converted into string using toString() method of Object class. The above string conversion can be done as follows also by using the static method valueOf() of String class.

String s2 = String.valueOf(buffer2);

2 thoughts on “Palindrome Delete Replace Reverse Java Example”

  1. class ReplaceAndReverse
    {
    public static void main(String args[])
    {
    StringBuffer str=new StringBuffer(“pavan”);
    System.out.println(str.setCharAt(0,’a’));
    System.out.println(str.reverse());
    }
    }

    Sir in this program at line no:

    replacemethod.java:6: ‘void’ type not allowed here
    System.out.println(str.setCharAt(0,’a’));
    ^
    1 error this error is coming what is this meaning??

    1. When a method returns does not return a value (void), you cannot keep it in println() method. This rule applies to C/C++ also.

      str.setCharAt(0,’a’)

      setCharAt() method replaces in the original buffer. After this method call, keep only str in println() method. you get output. Following works.
      public class Demo
      {
      public static void main(String[] args)
      {
      StringBuffer str=new StringBuffer(“pavan”);
      str.setCharAt(0,’a’);
      System.out.println(str.reverse());
      }
      }

Leave a Comment

Your email address will not be published.