Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i declare a static variable inside static member function in Java?

private static int Fibonoci(int n) {
static int first=0;
static int second=1;
static int sum;
if(n>0)

i am getting a error "Illegal Modifier" and if i remove static keyword there is no error and i need those variables to be static

like image 907
Raghu Avatar asked Jul 04 '13 12:07

Raghu


3 Answers

You can not declare varibale as static inside a method.
Inside method all variables are local variables that has no existance outside this method thats why they cann't be static.

static int first=0;
static int second=1;
static int sum;
private static int Fibonoci(int n) {
   //do somthing
}

You are trying to write code for fibonacci series and for that you don't need static variables for that just here is some links who describes the sol for that

http://crunchify.com/write-java-program-to-print-fibonacci-series-upto-n-number/

http://electrofriends.com/source-codes/software-programs/java/basic-programs/java-program-find-fibonacci-series-number/

like image 175
Ashish Aggarwal Avatar answered Oct 15 '22 11:10

Ashish Aggarwal


statics at function scope are disallowed in Java.

like image 26
Bathsheba Avatar answered Oct 15 '22 11:10

Bathsheba


The Root cause: Static Variables are allocated memory at class loading time because they are part of the class and not its object.

Now, if static variable is inside a method, then that variable comes under the method's scope and JVM will be unable to allocate memory to it.

like image 21
Prashant K Avatar answered Oct 15 '22 13:10

Prashant K