Java OCA OCP Practice Question 2821

Question

Given:

3. public class Main {  
4.   static int print(int i) { return i + 2; }  
5.   public static void main(String[] args) {  
6.     for(int x = 0; x < 5; print(x))   
7.       System.out.print(x + " ");  
8. } } 

What is the result?

  • A. 2 4
  • B. 0 2 4
  • C. 2 4 6
  • D. 0 2 4 6
  • E. Compilation fails.
  • F. Some other result occurs.


F   is correct.

Note

In a for loop, the iteration expression can be most any code statement that you want, such as the print() method call shown on line 6.

In this case, the result of the addition is not captured, so x's value never changes, therefore the for loop runs infinitely.

If the iteration expression read "x = print(x)", then B would be the correct answer.




PreviousNext

Related