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

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

Jump to Post

All 3 Replies

Re: Why infinite loop in this method 80 80

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

Re: Why infinite loop in this method 80 80

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

Re: Why infinite loop in this method 80 80

Thanks folks.

Be a part of the DaniWeb community

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