LearnFrenzy
Sign in Take a free test

Methods and Recursion · Predict the Output · Question 15

Reversing a string recursively Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    static String rev(String s) {
        if (s.length() <= 1) return s;
        return rev(s.substring(1)) + s.charAt(0);
    }

    public static void main(String[] args) {
        System.out.println(rev("Java") + " " + rev("ab") + " [" + rev("") + "]");
    }
}
  • A avaJ ba [] Correct
  • B Java ab []
  • C avaJ ab []
  • D aJav ba []
Correct Answer: Option A

Reverse the rest, then put the first character at the end.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links