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
Java Strings
Java String Methods
Java StringBuilder and Text Blocks
Exercises & Assignments
Reverse a string
Check if a string is a palindrome
Count the vowels in a string
Interview Questions & Answers
What is the difference between == and equals() in Java?
Why is String immutable in Java?
What is the difference between String, StringBuilder and StringBuffer?
What is the string pool in Java and what does intern() do?