[Java Basics] The difference and understanding of i++ and ++i

doubt

How to understand i++ and ++i in "for (int i = 2; i <= n; ++i)" and "for (int i = 2; i <= n; i++)" in java?

answer

In Java, both "i++" and "++i" are operators used to increment the variable i.

Specifically, "i++" is a postfix increment operator, its function is to use the value of the variable i first, and then add 1 to the value of i. For example, consider the following code:

int i = 2;
System.out.println(i++); // 输出2
System.out.println(i);   // 输出3

In the above code, the value of the variable i (2) is first printed out, and then the value of i is incremented by 1, so the value of i becomes 3 at the end.

On the contrary, "++i" is a prefix increment operator, its role is to first increase the value of i by 1, and then use the value of the variable i. For example, consider the following code:

int i = 2;
System.out.println(++i); // 输出3
System.out.println(i);   // 输出3

In the above code, the value of variable i is first increased by 1 (to 3), and then the value of variable i is printed out, so the output results are all 3.

To sum up, both "i++" and "++i" can be used to increment the value of variable i, but their execution order is different. "i++" is used first and then incremented, while "++i" is incremented first and then used.

What if they are all for loop printing?

If both for loops are used to print the value of the variable i, then no matter whether you use "i++" or "++i", the same result will be printed in the end.

For example, consider the following code:

int n = 5;

System.out.println("使用后缀递增操作符i++:");
for (int i = 2; i <= n; i++) {
    
    
    System.out.print(i + " "); // 输出2 3 4 5
}

System.out.println("\n使用前缀递增操作符++i:");
for (int i = 2; i <= n; ++i) {
    
    
    System.out.print(i + " "); // 输出2 3 4 5
}

In the above code, no matter whether "i++" or "++i" is used, the value of variable i will be printed out in order from 2 to 5 in the end.

This is because in this case, the execution order of the increment operator does not affect the result, because the value of the variable i has been used before printing, so whether it is used first and then incremented, or first incremented and then used, it will eventually print yield the same result.

Guess you like

Origin blog.csdn.net/weixin_44002043/article/details/131682399