Reverse a string

Description: Reverse the text "Java" to "avaJ". Do it with a loop and with StringBuilder.

Hint:

  • Go from the last index to 0 and join the characters.
  • StringBuilder has a reverse() method.

Solution

public class Main {
    static String reverseLoop(String s) {
        String result = "";
        for (int i = s.length() - 1; i >= 0; i--) {
            result += s.charAt(i);
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(reverseLoop("Java"));
        System.out.println(new StringBuilder("Java").reverse());
    }
}
Output

avaJ
avaJ

How it works

  • charAt(i) gives one character. The loop reads them from the end.
  • StringBuilder.reverse() is the shortest way.

Read Java String Methods.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.