• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

a static question

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
in this code, how can I access the variable i?
class Test {
static {
int i=20;
}
public static void main(String[] args) {
System.out.println(i); // compilation error
Test t = new Test();
System.out.println(t.i);// compilation error also
}
}

it seems that impossible to access the variable i... how can I use it in this case?
thx!
}
}
 
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Stephen Lee:
in this code, how can I access the variable i?
class Test {
static {
int i=20;
}
public static void main(String[] args) {
System.out.println(i); // compilation error
Test t = new Test();
System.out.println(t.i);// compilation error also
}
}

it seems that impossible to access the variable i... how can I use it in this case?
thx!
}
}


Hello Stephen ,
well, u can never access var i as it not a memeber variable of class. Instead it a local to static block.

static {
int i=20;
}

If u declare it as
static int i;
static {
i=20;
}
then only u can access it.
HIH
Rashmi
 
Ever since I found this suit I've felt strange new needs. And a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic