Beware of Static Finals

Beware of Static Finals

Consider this scenario, you define a public static final variable in one java file, and access the variable in other java file. Now, if you change the value of static variable and compile only the changed java file, you’ll get the wrong result. The example below will make it clear(tested on Sun JDK1.2.2 on WinNT).
Let’s have as:

 	public class StaticFinals {		public static final int VALUE = 10;	}

Access VALUE from other file called

 	public class TestStaticFinals {		public static void main	(String args[]){			int staticvalue = StaticFinals.VALUE;			System.out.println(" Value is " + staticvalue );		}	}

Now compile both the files and run TestStaticFinals.class

It will print “Value is 10.”Now change as below:

 	public class StaticFinals {		public static final int VALUE = 20;	}

Then compile only, (because you have changed only this file) and run TestStaticFinals.class.

Still it will print “Value is 10”, even though you are expecting it to return “Value is 20.”

What does that mean? It means your java compiler copies the value of VALUE at the compile time in to TestStaticFinals.class. So whenever you change the value of public static final variables, remember to recompile all dependent files also.

See also  Redefining Energy Management: Advanced Solutions for Modern Buildings

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist