• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variable

 
Nilesh Raje
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Friends,

I have a confusion here .This is from EFS mock test.

public class Test2{

public int aMethod() {
static int i = 0;
i++;
return i;
}
public static void main (String args[]) {
Test2 test = new Test2();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}

wy does this not compile..! It says illegal start of expression on static keyword..! I tried making the method static still it complains..!
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
" static int i = 0"

you are trying to declare a static variable within a method. This is not legal. static variables are class variables only. Declared outside of methods.

Mark
 
Santana Iyer
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just to add the only modifier you could use for local variable (declared inside method including parameters) is
final. no other modifier is allowed.
[ September 02, 2005: Message edited by: Santana Iyer ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic