An analysis of the execution of the for loop in Java

  • 2020-04-01 03:40:04
  • OfStack

This article illustrates the execution of a for loop in Java. Share with you for your reference. Specific analysis is as follows:


public class Test01{
public static void main(String[] args) { 
  int i = 0 ;
  for(foo('A');foo('B')&&i<3;foo('C')){
  i++ ;
  foo('D') ;
  }
}
public static boolean foo(char c){
System.out.print(c + " ");
return true ;
}
}

What is the output of this program?
Yes, it is: A, B, D, C, B, D, C, B

Why is that? Because the for loop executes the 'A' before the first semicolon, then' B', and then executes the code in the for loop if the condition is met
Then you jump to the 'C' after the second semicolon and you execute it, and then you compare whether' B' satisfies the condition, and then you continue into the for loop
That is, the BDC keeps looping until when it runs B, the latter condition is not satisfied, and outputs the last 'B'.

Now, do you have a good understanding of the for loop?

I hope this article has been helpful to your Java programming.


Related articles: