Difference between for and while

1  package com.ibeve.demo;
 2  
3  public  class ForDemo {
 4  
5      public  static  void main(String[] args) {
 6  
7          /** 
8           * for(initialization expression; loop expression; operation expression after loop ){ execute the statement; } Note: as soon as the condition is satisfied, go to the loop body immediately, after the loop body, go to x++
 9           */ 
10          for ( int x = 0; x < 3; x++ ) {
 11              System.out.println( "x=" + x);
 12          }
 13          // Scope problem with x
 14          // System.out.println("x=====" + x); 
15      
16         int y = 0 ;
 17          while (y < 3 ) {
 18              System.out.println("y=" + y);
 19              y++ ;
 20          }
 21          System.out.println("y=====" + y );
 22          /** 
23           * 1. Variables have their own scope. For for, if the increment used to control the loop is defined in the for statement.
24           * Then the variable is only valid in the for statement. After the for statement is executed, the variable is released in the memory.
25           * 
 26           * 3. for and while can be interchanged. If you need to define loop increments, for is more appropriate.
27           * 
 28           * Summary:
 29           * When to use a loop structure?
30          * Use the loop structure when you want to execute certain statements many times.
31           */ 
32      }
 33  
34 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324971110&siteId=291194637