How to Rotate a String in Java

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); } }
Code language: Java (java)

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:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments