This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 19651
    
  18

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
 
 
subject: static in a method
 
Similar Threads
Question ID :957734680770
say it ain't so!
Static method and non-static data
no assignment is needed here?