Today I will briefly talk about a misunderstanding about Java. I believe that many friends who are just starting to learn Java will encounter this problem. Although the problem is very simple, it is often easy to get confused. Let me talk about the difference between i++ and ++i of Java.
Let's take a look at the code first:
<span style="font-size:18px;">public class test {public static void main(String[] args) {int i = 0; for (int j = 0; j < 10; j++) {i=i++;}System.out.println("last result of i"+i);}}</span>You can see the result at a glance, what is the result? Is it 10?
I believe there are still many friends who look at it for the first time and think that the answer is 10, and the correct answer is: 0;
When I first started learning C and java, the teacher talked about the self-increase form: i++ and ++i;
In fact, the difference is that i=i++ is assigned to the value first and then increasing, so no matter how many times the cycle is, the i on the left is always 0, and the final result is 0. Changing it to i=++i can achieve the effect, and ++i is assigned to the value first and then increasing.
You can understand it like this, look at the code:
<span style="font-size:18px;">public class test {public static void main(String[] args) {int i = 0; for (int j = 0; j < 10; j++) {i=i++;}System.out.println("i's final result"+i);}public static int count(int i) {// TODO Auto-generated method stub//Select to save the initial value, the temporary variable area opened by JVA is int temp=i;// Do auto-increment i = i++;//Return the original value return temp;}}</span>Therefore, to achieve self-increase, you can use i=++i, but generally use i++ directly, which is better; this is also considered a self-increase trap in JAVA.
The above article deeply understands the difference between i++ and ++i in Java is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.