Understand the difference between i++ and ++i in java

  • 2020-05-19 04:46:09
  • OfStack

Today, I would like to talk about a misunderstanding about java. I believe that many friends who have just started to learn java will encounter this problem. Although the problem is very simple, it is easy to get confused.

First 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 The end result of "+i);
	}
	
}
</span>

You can see the result by 1. What is the result? Is 10?

I believe there are still many friends first look, think the answer is 10, the correct answer is: 0;

When I first learned C and java, my teacher taught me the self-enrichment form: i++ and ++i;

In fact, the difference is that i=i++ is self-incrementing, so no matter how many times you loop, i on the left is always 0, and the final result is 0. Changing i=++i can achieve the effect, while ++i is self-incrementing before assigning.

You can understand it by looking 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 The end result of "+i);
	}
	
	
	public static int count(int i) {
		// TODO Auto-generated method stub
		// Select save initial value ,JVA Open up the zone of temporary variables 
		int temp=i;
		// Do on the 
		i = i++;
		// Return the original value 
		return temp;
		

	}
}
</span>

So you can use i=++i if you want to do self-augmentation, but you can use i++ if you want to do 1, which is better; This is also a self-reinforcing trap for JAVA.


Related articles: