views:

128

answers:

4

Hi, I am having a static method .In the method when I decalare a variable , it was showing an error in eclipse saying that the variable should be decalared as final. Can I know the reason for this , y should a variable in a static method be declared as final? I am writng an Android application where I should pass as an argument current Context of that application. So, when I pass the current context to the method and trying to copy it in a local variable , I am getting this error saying that the variable should be declared as final. my method is like this:

public static void myfunc(Context ctx, int a)  
{                                     
  Context myctx=ctx;                      
}     

error is showing at line where Context myctx=ctx; is declared and asking me to declare it as final.

+1  A: 

Its probably being triggered if you declare a variable and then dont modify it afterwards.

The suggestion is that by declaring it final you allow certain JVM optimisations.

Visage
+1  A: 

No its not the case. You can make non final variable in static method .

org.life.java
+6  A: 

The regular settings of the compiler don't do this. You are not forced to declare it final.

There are 3rd party tools (like checkstyle and pmd) that can add errors and warnings. In this case the variable is changed nowhere else in the method, so it can be declared final

And if you have an anonymous class instantiated below the variable, and use the variable there (but you are not showing this to us) - then it must be declared final.

Bozho
+3  A: 

Not necessarily. You can have a non final variable inside the static function.

Classic example:

public static void main(String args[])
{
   int i = 10;
} 
Dheeraj Joshi
+1 for reminding the classic example
chedine