Java ProgramsRecursionPrint String Characters Using Recursion

Print String Characters Using Recursion in Java

beginner·  Recursion  ·  Recursion

Problem

Walking through a string one character at a time doesn't require a loop — a recursive call that advances the index by one and stops once it reaches the string's length covers the same ground.

Given a string, print each of its characters on its own line using recursion.

Input
Java
Output
J a v a

Java Program

Java
public class PrintStringCharactersRecursion { static void printChars(String s, int index) { if (index == s.length()) return; // every character has been printed System.out.println(s.charAt(index)); printChars(s, index + 1); } public static void main(String[] args) { String s = "Java"; printChars(s, 0); } }

Output

J a v a

Core Logic

Printing the character at the current index, then recursing on the next index, visits every character in order without any explicit loop.

How It Works
  1. 1printChars(s, index) takes the string and the position to print next.
  2. 2The base case if (index == s.length()) return; stops the recursion once every character has been visited.
  3. 3Otherwise, s.charAt(index) prints the current character, then the method calls itself with index + 1.
  4. 4Each call handles exactly one character before handing off to the next call.
For "Java", the calls print J, then a, then v, then a, before the fifth call hits the base case and stops.
💡

Key Point: The base case comparing index to s.length(), not some fixed number, is what makes this work for a string of any length without changing the code.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: One call handles each of the n characters, and all n calls stay on the call stack at once until the base case is reached and they unwind.

Key Concepts

recursionbase caseString.charAt()

Related Programs