Java Program to Print Characters of String to New Line Without Using Loop
In this post, we will look at how to print each character of a string in a new line without using loops in Java.
Logic:
We will make use of recursion to solve this problem.
- Create a method print
- Base condition is (str.length() == index), this is the condition when recursion breaks
- Code uses the ‘index’ variable for indicating the position of each character
Program
Let’s have a look at the program.
// Java program to demonstrate
// how to print characters
// of String on a new line
// without loop
public class PrintStringDemo {
public static void main(String[] args) {
// Call method with
// index as 0
print("DummyString", 0);
}
// recursively prints
// each character of str
// on a new line
public static void print(String str, int index) {
if (str.length() == index) {
return;
}
System.out.println(str.charAt(index));
print(str, ++index);
}
}
Output:
D u m m y S t r i n g