Title:
public class test{
public static void Main (string[] args) {
int count = 0;
for (int i=0;i<10;i++) {
Count = count++;
}
System.out.println ("count=" +count);
}
}
This code outputs a result of 0, not 10.
count++ is an expression that has a return value, and its return value is the value of the pre-addition, which is handled by Java: first copy the value of Count to a temporary variable area, then add 1 to the count variable, and finally return the value of the temporary variable area.
Therefore, the execution of the above code is: ①JVM Copy the Count value to the temporary variable area, ②count value plus 1, this time the count value is 1;③ return the value of the temporary variable area, note that this value is 0, not modified, ④ the return value is assigned to count, at this point, the count value is reset to 0.
After a loop, the count value is still 0, which is the case for each subsequent loop, and ultimately, the count value is always 0, regardless of the number of cycles.
This article from "brightaries" blog, declined reprint!
Java self-increasing traps