Hi everyone,

I'm just wondering why this method below causes an infinite loop to happen. I thought it would run once and then stop. Anyone can explain this? that'll be great.

public String printer(String s){
		if (s.length() >= 5){
			System.out.println("I'm  " + s + " And my length = " + s.length());
		return printer(s);

Recommended Answers

All 3 Replies

return printer(s); calls printer(s) again, which executes down to the last line where it executes return printer(s); etc infinitely

if we need to execute the loop only once there is no need of recursion
using simply return; will help you to get the desired output

Thanks folks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.