When I assign the value++ of a static int to another int, it is performing the assignments in an order that doesn't seem to follow the order of operations for Java. Shouldn't it do the ++ before the =?
public class Book
{
private int id;
private static int lastID = 0;
public Book ()
{
id=lastID++;
}
}
In the first book I construct, the id is 0. Shouldn't it be 1 since lastID++ should happen first?
Your are using the postfix ++ operator. This will increment after the variable is used (in your case is assignment).
If you want to increment before assignment use this
id = ++lastID;
This is known as the prefix ++ operator.
Shouldn't it do the ++ before the =?
--> Yes ++ is evaluated first as below :
Your expression :
id = lastID++;
is equivalent to following expression
temp = lastId; // temp is 0
lastID = lastID + 1; // increament, lastId becomes 1
id = temp; // assign old value i.e. 0
So you have id as 0, you should use, pre-increament operator(++) in this case as :
public class Book
{
private int id;
private static int lastID = 0;
public Book ()
{
id = ++lastID; // pre-increament
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With