Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Static initializer  RSS feed

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • 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
 
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thank you so much for your clarification.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!