Originally posted by David Mroczkowski:
I came across a practice test question that had this in the for loop statement. I thought this would not compile. Am I wrong?
int i = 0;
for ( method1(i) ; method1(i); method2(i)) {
// code
}
boolean method1(int i) { i++ ;
return true;
}
boolean method2(int i) {i++;
return !(method1(i));
}
system.println(i);
As others have answered, the for loop doesn't cause any compiler errors, but the issues with static and member methods will. Also, there is no class declaration, which will definitely cause a compiler error. Of course, it is probably safe to assume that this code IS inside a class, however, that brings the question of where the println() method call belongs. If we make some modifications, we can get it to compile and clarify some assumptions:
Also assuming an appropriate main() method that invokes this code, the next question is how does it act?
Since i is local and passed to various functions, its value never changes within the doIt() method. Also, method1() always returns true. This leads me to the conclusion that the for loop will repeatedly print a "0" to the console. In fact, it looks like an infinite loop to me, with the modifications made.
I guess this all hinges on the assumptions I stated earlier. If these are not similar to the actual code example, then please post the full code as it is supposed to be. At the very least include the class declaration and put all executing code into a method.
With all that said, the code as-is will NOT compile. Some assumptions and modifications need to be made to do so.
Regards,
Layne