• 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

Static initializer

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
The following code will give
1: public class Q8
2: {
3: int i = 20;
4: static
5: {
6: int i = 10;
7:
8: }
9: public static void main(String[] args)
10: {
11: Q8 a = new Q8();
12: System.out.println(a.i);
13: }
14: }
A) Compilation error, variable "i" declared twice.
B) Compilation error, static initializers for initialization purpose only.
C) Prints 10.
D) Prints 20.
The answer is 20. My question is, for those variables that are within static initializer, do they need to be declared as static as well? "i" in the above case is a non-static variable. but it should exist since it's initialized the frist time in the static initialization.
lydia
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the variable i declared within the static block is only visible and accessible within that block and not outside of it. The member variable i we access on line 12 is the one declared and initialized on line 3.
Moreover, you cannot declare a static variable within a static block, that is, you cannot put the "static" keyword at the beginning of line 6.
Bottom line is variables i declared on line 3 and 6 are DIFFERENT. The one on line 6 is out of scope when the static block ends.
 
lydia westland
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you so much for your clarification.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic