• 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:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Strange code

 
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class d {
int a[] = new int[5];
int i = 1;
void increase(int a[]) {
a[i] = 2;
}
public static void main(String args[]) {
d f = new d();
f.increase(a);
System.out.println(a[2]);
}
}
this code is giving error that a is not static. I don't understand why it is giving the error
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
when u r accessing a instance variable from the a static method ( main is a static method ) the instance variable must also b static. so u r method invocation would work only if u say
f.increase(f.a);
else u have to declare a local array of integers in main and then pass it to the method say
public static void main(String[] args)
{
int a[] = new int[5];
f.increase(a);
} -- this will not give you
the error that a is not static
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Shabbir,
problem with your code is that u r trying to access instance variable a in main without a object of class d.
your main should be like this==>
public static void main(String args[]) {
d f = new d();
f.increase(f.a);
System.out.println(f.a[2]);
}
I hope this helps you.
ashish
reply
    Bookmark Topic Watch Topic
  • New Topic