The difference between i ++ and ++ i

The difference between i ++ and ++ i

The difference between the two simple output results is the same:

++ i is to change the value of i by adding 1 before using the value of i; and i ++ is to use the value of i before changing its value and adding.

Sample code 1 [Result difference]:

  int a=6; int b=6; System.out.println(a++); System.out.println(++b); 

Output result:

 

 Sample code 2 [same result]:

  int a=6; int b=6; a++; ++b; System.out.println(a); System.out.println(b); 

Output result:

 

The difference in the for loop [the same output result]:

Only the form inside the for loop is different: when the i ++ loop and the ++ i loop are inside the for loop, although the form is obviously different, the output result can be the same

Sample code 3:

        int i=0;
        int j=0;
        for(;i<5;i++){
            System.out.println(i);
        }
        System.out.println(i);
        for(;j<5;++j){
            System.out.println(j);
        }
        System.out.println(j);

Output result:

 

 

It can be seen that there is no difference in the usage.

But internal use is different.

The above for loop program is the same as the following program, but the internal form is different.

Sample code 4:

        i=0;
        while(i<5){
            System.out.println(i);
            i++;
        }
        System.out.println(i);
        j=0;
        while(j<5){
            System.out.println(j);
            ++j;
        }
        System.out.println(j);

Output result:

 

Guess you like

Origin www.cnblogs.com/yanghe123/p/12734894.html