• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static in a method

 
Krishna Tota
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

public class Test{
public int aMethod()
{
static int i=0;
i++;
return i;
}
pblic static void main(String a[])
{
Test t=new Test();
t.aMethod();
int j=t.aMethod();
System.out.println(j);
}
}
What is the rong with this code.
please explain in brief.
Thanks.
 
Rob Spoor
Sheriff
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java does not support static variables inside methods like C and C++ do. Instead, you should make the variable a class or instance variable:
 
Shahnawaz Shakil
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can not mark local variable as static
 
Arijit Daripa
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Krishna Tota:
Hi,

public class Test{
public int aMethod()
{
static int i=0;
i++;
return i;
}
pblic static void main(String a[])
{
Test t=new Test();
t.aMethod();
int j=t.aMethod();
System.out.println(j);
}
}
What is the rong with this code.
please explain in brief.
Thanks.


Method-local variables( those declared inside a method) can't have the modifiers public, private, protected, transient, syncronized, abstruct, strictfp, static. They can only have the modifier final.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic