• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Devaka Cooray
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Junilu Lacar
  • paul wheaton
  • Paul Clapham
Saloon Keepers:
  • Piet Souris
Bartenders:

static in a method

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22899
132
Eclipse IDE Spring TypeScript Quarkus Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can not mark local variable as static
 
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 coderanch, private, protected, transient, syncronized, abstruct, strictfp, static. They can only have the modifier final.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic