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
A palindrome check is performed first by comparing the string with its reverse, and the rotation logic only executes if this check passes, demonstrating conditional string rotation.