w3resource

Java String Exercises: Check if two given strings are rotations of each other

Java String: Exercise-52 with Solution

Write a Java program to check if two given strings are rotations of each other.

Sample Solution:

Java Code:

import java.util.*; 
class Main
{
    static boolean checkForRotation (String str1, String str2)
    {
        return (str1.length() == str2.length()) && ((str1 + str1).indexOf(str2) != -1);
    }
    public static void main (String[] args)
    {
        String str1 = "ABACD";
        String str2 = "CDABA";
		    System.out.println("The given strings are: "+str1+"  and  "+str2);
		    System.out.println("\nThe concatination of 1st string twice is: "+str1+str1);

        if (checkForRotation(str1, str2))
        {
		        System.out.println("The 2nd string "+str2+"  exists in the new string.");	
            System.out.println("\nStrings are rotations of each other");
        }
        else
        {
          	System.out.println("The 2nd string "+str2+"  not exists in the new string.");	
            System.out.printf("\nStrings are not rotations of each other");
        }
    }
}

Sample Output:

The given strings are: ABACD  and  CDABA

The concatination of 1st string twice is: ABACDABACD
The 2nd string CDABA  exists in the new string.

Strings are rotations of each other

Pictorial Presentation:

Java String Exercises: Check if two given strings are rotations of each other

Flowchart:

Flowchart: Java String Exercises - Check if two given strings are rotations of each other

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to count and print all the duplicates in the input string.
Next: Write a Java program to match two strings where one string contains wildcard characters.

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH