devxlogo

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 StaticFinals.java as:

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

Access VALUE from other file called TestStaticFinals.java:

 	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 StaticFinals.java as below:

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

Then compile only StaticFinals.java, (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  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

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