Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java assignment of static variable++

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?

like image 504
user1901074 Avatar asked Dec 04 '25 11:12

user1901074


2 Answers

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.

like image 171
Babar Ali Avatar answered Dec 06 '25 00:12

Babar Ali


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
  }
}
like image 23
Nandkumar Tekale Avatar answered Dec 06 '25 00:12

Nandkumar Tekale