Rotate String Only if Palindrome

This program rotates string only if it is palindrome.

Problem Statement

Write a Java program to rotate "madam" by 2 positions only if palindrome.

Source Code

1 public class RotateIfPalindrome {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Rotate If Palindrome");
4 String str="madam";
5 String rev=new StringBuilder(str).reverse().toString();
6 if(str.equals(rev)){
7 int d=2;
8 String rotated=str.substring(d)+str.substring(0,d);
9 System.out.println("Rotated string: "+rotated);
10 } else System.out.println("Not palindrome, no rotation");
11 }
12 }

Program Output

Eduinq Rotate If Palindrome
Rotated string: damma

Explanation

Palindrome check performed first. - Rotation applied only if palindrome. - Together demonstrates conditional rotation. Conclusion: Shows how to rotate string with palindrome constraint.

Quick Links to Explore