Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java static final values replaced in code when compiling?

In java, say I have the following

==fileA.java==
class A
{  
    public static final int SIZE = 100;
}  

Then in another file I use this value

==fileB.java==  
import A;
class b
{
      Object[] temp = new Object[A.SIZE];
}

When this gets compiled does SIZE get replaced with the value 100, so that if I were to replace the FileA.jar but not FileB.jar, would the object array get the new value or would it have been hardcoded to 100 because that's the value when it was originally built?

like image 489
Without Me It Just Aweso Avatar asked Mar 02 '11 20:03

Without Me It Just Aweso


People also ask

Can final and static be used together in Java?

The terms static and final in Java have distinct meanings. The final keyword implies something cannot be changed. The static keyword implies class-level scope. When you combine static final in Java, you create a variable that is global to the class and impossible to change.

How do I change the value of the final static variable in Java?

In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.

Is final always static in Java?

No, absolutely not - and it's not a convention. static and final are entirely different things. static means that the field relates to the type rather than any particular instance of the type. final means that the field can't change value after initial assignment (which must occur during type/instance initialization).

Can we declare static variable as final?

Static variables are normally declared as constants using the final keyword. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.


2 Answers

Yes, the Java compiler does replace static constant values like SIZE in your example with their literal values.

So, if you would later change SIZE in class A but you don't recompile class b, you will still see the old value in class b. You can easily test this out:

file A.java

public class A {
    public static final int VALUE = 200;
}

file B.java

public class B {
    public static void main(String[] args) {
        System.out.println(A.VALUE);
    }
}

Compile A.java and B.java. Now run: java B

Change the value in A.java. Recompile A.java, but not B.java. Run again, and you'll see the old value being printed.

like image 197
Jesper Avatar answered Oct 07 '22 00:10

Jesper


You can keep the constant from being compiled into B, by doing

class A
{  
    public static final int SIZE;

    static 
    {
        SIZE = 100;
    }
}  
like image 21
MeBigFatGuy Avatar answered Oct 07 '22 00:10

MeBigFatGuy