Check if Two Strings Are Rotations of Each Other in Java — Definition, Examples and Program

Learn how to check whether two strings are rotations of each other in Java using logical string comparison without using complex libraries.

Check if Two Strings Are Rotations of Each Other in Java

Two strings are said to be rotations of each other if one string can be obtained by rotating the other string any number of times.

This is a popular interview problem that tests understanding of string logic and pattern matching.

Understanding String Rotation

If str2 is a rotation of str1, then it must:

Example 1

Input:

Output: Strings are rotations of each other

Example 2

Input:

Output: Strings are rotations of each other

Example 3

Input:

Output: Strings are NOT rotations of each other

Logic Explanation

  1. Check if both strings have equal length.
  2. Concatenate the first string with itself.
  3. Check if the second string exists inside the concatenated string.
  4. If yes, the strings are rotations.

Java Program to Check String Rotation


import java.util.Scanner;

public class StringRotation {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first string: ");
        String str1 = sc.nextLine();

        System.out.print("Enter second string: ");
        String str2 = sc.nextLine();

        if (str1.length() != str2.length()) {
            System.out.println("Strings are NOT rotations of each other");
        } else {
            String combined = str1 + str1;

            if (combined.contains(str2)) {
                System.out.println("Strings are rotations of each other");
            } else {
                System.out.println("Strings are NOT rotations of each other");
            }
        }
    }
}

Sample Output


Enter first string: ABCD
Enter second string: CDAB
Strings are rotations of each other

Important Notes

Practice Challenges

  1. Check rotation without using contains().
  2. Ignore case sensitivity while checking rotation.
  3. Find how many rotations are possible for a string.

This problem is a classic example of combining logic with string manipulation and is frequently asked in Java interviews.