Java assignment static variable
•
Java
When I assign the value of a static int to another int, it performs the assignment in an order that does not seem to follow the Java operation order Shouldn't it be done before =?
public class Book { private int id; private static int lastID = 0; public Book () { id=lastID++; } }
In the first book I built, the ID was 0 It should not be 1, because should lastid happen first?
Solution
– > Yes, first evaluate the following:
Your expression:
id = lastID++;
Equivalent to the following expression
temp = lastId; // temp is 0 lastID = lastID + 1; // increament,lastId becomes 1 id = temp; // assign old value i.e. 0
So your ID is 0. In this case, you should use pre increase operator():
public class Book { private int id; private static int lastID = 0; public Book () { id = ++lastID; // pre-increament } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码