File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes static in a method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static in a method" Watch "static in a method" New topic
Author

static in a method

Krishna Tota
Ranch Hand

Joined: Mar 22, 2008
Posts: 40
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

Joined: Oct 27, 2005
Posts: 19761
    
  20

Java does not support static variables inside methods like C and C++ do. Instead, you should make the variable a class or instance variable:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Shahnawaz Shakil
Ranch Hand

Joined: Aug 04, 2008
Posts: 57
You can not mark local variable as static
Arijit Daripa
Ranch Hand

Joined: Aug 09, 2008
Posts: 142
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.


SCJP 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static in a method