Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Mar 6, 2000

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.

Nilesh Shah
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date