Search code examples
javastatic-variables

Is this a valid way to initialize static variables?


I have a big file of constants. Is this a valid way to initialize them?

private static int i = 0;

public static final int ITEM_GOLD = i++;
public static final int ITEM_ZINC = i++;
public static final int ITEM_TIN = i++;
....

ITEM_GOLD should equal 0, ITEM_ZINC should equal 1, ITEM_TIN should equal 2 and so on.


Solution

  • Yes, this should work. However, I would recommend to use the enum class instead. If the number really has some semantic (not just an arbitrary discriminator of a constant) then this is ok, otherwise enum is better (can be used in switch, the code is more readable, etc..)

    If you don't want to introduce a new file, you may want to declare the enum in the surrounding class:

    public TheClass {
       ...
       enum Item {
         GOLD, ZYNC, TIN
       }
       ...
    }