How to Rotate a String in Java

0 min read 116 words

Rotating a String in Java is a common interview question, and albeit it quite a simple one, it tests many fundamental concepts. Did I mention that it can also be done fairly quickly too!

Rotating a String in Java

public class Rotater {

    public static void main(String...args) {

        Rotater r = new Rotater();

        System.out.println(r.rotateLeft("test", 1));
        System.out.println(r.rotateRight("test", 1));

    }

    private String rotateLeft(String value, int n) {
        return value.substring(n) + value.substring(0, n);
    }

    private String rotateRight(String value, int n) {
        return rotateLeft(value, value.length() - n);
    }

}

With the above code, we can rotate a string both left and right, but we don’t take into account any edge cases, exception handling, input validation or out of bounds problems.

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags