Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant values not reflected at run time [closed]

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?

like image 742
Saurabh Kumar Avatar asked Dec 28 '22 07:12

Saurabh Kumar


1 Answers

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

See also:

  • Is Java guaranteed to inline string constants if they can be determined at compile time
  • Are all compile-time constants inlined?
like image 86
Bozho Avatar answered Jan 04 '23 18:01

Bozho