Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Final variable inlining - WHY?

843810Jul 28 2004 — edited Jul 29 2004
Have noticed that the java compiler inlines referenced values of final constants during compilation. What this essentially means is that if the value of the constant is changed and the file containing the constant is recompiled; the file referencing it doesn't get recompiled and has stale value of this constant. The code below might be of some help in articulating this:

Lets say we have a class with two constants:
public class Const
{
public final int one = 11;
public final int two = 21;
}

And another class that references these primitive constants (note that these are not static variables)
public class UseCons
{
public void printCons()
{
Const con = new Const();
System.out.println("One : "+con.one);
System.out.println("Two : "+con.two);
}

public static void main(String str[])
{
UseCons useCons = new UseCons();
useCons.printCons();
}
}

Now lets compile these two classes [javac *.java]
And execute the main class [java UseCons]. Here's the out put from the console
One : 11
Two : 21

Now lets change the definition of Const.java
public class Const
{
public final int one = 1;
public final int two = 2;
}

Lets compile this changed Const.java [javac Const.java]
And execute the main class again [java UseCons]. Here's the output now
One : 11
Two : 21

As you can see, even after changing the value of these constants, the change doesn't reflect in the class referencing these values. The reason for this is that the java compiler is inlining these values. Here's the decompiled UseCons.class

import java.io.PrintStream;

public class UseCons
{

public UseCons()
{
}

public void printCons()
{
Const const1 = new Const();
const1.getClass();
System.out.println("One : " + 11);
const1.getClass();
System.out.println("Two : " + 21);
}

public static void main(String args[])
{
UseCons usecons = new UseCons();
usecons.printCons();
}
}

As you can see the compiler has put the value of the constants in the code (inlined the constants). This doesn't seem right to me, because it is very much possible that I may want to change and recompile the constants file without wanting to recompile (and possibly redeploy) the file using these constants.

Does anybody here have any information about what is the rationale behind this inlining, OR is this just another thing that doesn't make sense and one has to deal with anyway.

And hey techies - DON'T FORGET TO PARTY!!!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 26 2004
Added on Jul 28 2004
7 comments
637 views