javaconstants

Constant values not reflected at run time


Suppose that you compile the following two classes. The first is meant to represent a client; the second, a library class.

public class Test{
    public static void main(String[] args) {
        System.out.println(Lib.FIRST + " " +
                           Lib.SECOND + " " +
                           Lib.THIRD);
    }
}


public class Lib{
    private Lib() { }; // Uninstantiable
    public static final String FIRST = "the";
    public static final String SECOND = null;
    public static final String THIRD = "set";
}

prints:

{the null set}

Now suppose that you modify the library class as follows and recompile it but not the client program:

public class Lib{
    private Lib() { }; // Uninstantiable
    public static final String FIRST = "physics";
    public static final String SECOND = "chemistry";
    public static final String THIRD = "biology";
}

prints:

{the chemistry set}

Why is the SECOND value changed but not the FIRST or THIRD?


Solution

  • That's a known caveat - constants are inlined when you compile your client program, so you have to recompile it as well.

    See also: