1

Is it safe to assume that the following constants in Java 8+ are guaranteed to always be assigned the same values i.e. that the compiler will not reorder the statements for any reason, such as optimization?

public class MyClass {
    
    private static int TIP = 0;
    
    public static final int A = TIP++;
    public static final int B = TIP++;
    public static final int C = TIP++;
    public static final int D = TIP++;
    
}
RTF
  • 6,214
  • 12
  • 64
  • 132
  • Yes, the assignment can be reordered (as in, D could be assigned before A), but the values assigned to each variable will always be the same. – Andy Turner Jun 30 '20 at 17:09
  • @AndyTurner but... the assigned values are dependant on the order, so if they are reordered, the values will be different?? – RTF Jun 30 '20 at 17:12
  • The increments and assignments are separate operations. Imagine the results of the four increments could be pushed onto the stack; you'd have to pop them off and assign them in reverse order. (I'm not saying this does happen; I'm saying it's not disallowed). – Andy Turner Jun 30 '20 at 17:21

0 Answers0