Java: Reverse string

Line flip is the simplest algorithmic problem, which is sometimes set at interviews. The correct way to flip a line is to use a function from the standard library, but for learning purposes it is useful to implement it yourself.

One of the algorithms looks like this: we build a new line by sorting the characters of the source line in reverse order.

public static void main(String[] args) {
    reverseString("Game Of Thrones");  // => senorhT fO emaG
static String reverseString(String str)
    var index = str.length() - 1;
    var reversedString = "";

    while (index >= 0) {
        var currentChar = str.charAt(index);
        reversedString = reversedString + currentChar;
        index = index - 1;

    return reversedString;

Let's sort the function line by line:

  • var index = str.length () - 1 write in the new variable the index of the last character of the string (recall that indices start from zero)
  • String reversedString = "" initialize the string where we will write the result
  • while (index> = 0) condition - repeat the loop body until the current index has reached 0, that is, to the first character
  • var currentChar = str.charAt(index) we take a character from the string by the index, the current value of the counter acts as the index - that is, in each iteration the index will be different
  • reversedString = reversedString + currentChar add this character to the result string.
  • index = index - 1 update counter
  • return reversedString when the loop is complete, return the result string.

When working with strings, programmers often make the mistake of “breaking the line”. In case of incorrect selection of the initial value of the counter or an error in the predicate of the cycle, a situation may arise in which a non-existent symbol is accessed.

It is especially often forgotten that the characters in the lines are indexed from 0, therefore the index of the first character is 0, and the last one is less than the length of the string.


Implement the mysubstr function, which extracts substrings of a specified length from a string. It takes two arguments as input: a string and a length, and returns a substring starting with the first character:

Call example:

var str = 'If I look back I am lost';
mysubstr(str, 1); // => 'I'
mysubstr(str, 7); // => 'If I lo'

Use the same approach as in a function to flip a line from a lesson: collect the result string in a loop, looping through the starting line until a certain point.

If you got stuck and don't know what to do, you can ask a question in our huge and friendly community