Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop with no parameters in Java

I am looking at somebody else's code and I found this piece of code:

for (;;) {

I'm not a Java expert; what is this line of code doing?

At first, I thought it would be creating an infinite loop, but in the very SAME class this programmer uses

while(true)

Which (correct me if I'm wrong) IS an infinite loop. Are these two identical? Why would somebody change their method to repeat the same process?

Any insight would help,

Thanks!

like image 296
Doug Molineux Avatar asked May 18 '11 22:05

Doug Molineux


People also ask

Can you have an empty for loop Java?

For creating a loop that runs infinitely, we can use empty statements. However, if we use break statements inside the body of the loop, then the loop can terminate. If we want to create a for-loop or while loop that has an empty body, we can use an empty statement.

Can for loop be without condition?

Yes it is perfectly correct to do so.

Can you have a method with no parameters?

Note that methods do not have to take any parameters, but you still need the parentheses after the method name. Procedural abstraction allows a programmer to use a method by knowing in general what it does without knowing what lines of code execute.


2 Answers

Remember the three clauses of the for() are [1] initialization [2] termination and [3] increment. Since the termination clause is empty the loop never terminates. This is directly taken from C syntax.

like image 137
wberry Avatar answered Oct 05 '22 11:10

wberry


Those two lines would have the same effect. I can't think of a good reason to use the first one unless you like to confuse people. I guess it's less characters.

like image 45
Dave Avatar answered Oct 05 '22 12:10

Dave