Can i declare a static variable inside static memb

2019-03-14 04:49发布

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

9条回答
孤傲高冷的网名
2楼-- · 2019-03-14 04:57

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/

查看更多
Emotional °昔
3楼-- · 2019-03-14 05:01

You can't declare a static variable inside a method, static means that it's a variable/method of a class, it belongs to the whole class but not to one of its certain objects. This means that static keyword can be used only in a 'class scope' i.e. it doesn't have any sense inside methods.

I don't know what you are trying to achieve, but if you really want these variables to be static then you can declare them as static fields in your class.

查看更多
等我变得足够好
4楼-- · 2019-03-14 05:02

statics at function scope are disallowed in Java.

查看更多
Viruses.
5楼-- · 2019-03-14 05:02

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.

查看更多
一夜七次
6楼-- · 2019-03-14 05:02

Local variables cannot be declared static. In other words Static doesn't apply to local variables.

And I didn't see any use of declaring them static there.

Follow JLs on static fields

A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

查看更多
不美不萌又怎样
7楼-- · 2019-03-14 05:08

This varibles called Local Variables, they are inside method scop or constructor, they can't be instance or class variables.

private static int COUNT;// Class Variable
private static int Fibonoci(int n) {
 int a =3 ; // local variable
}

I need those variables to be static, okey , Why do you need this? because static variables used for special purpuse, however, you can create static fields like I did above code.

查看更多
登录 后发表回答