wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static initializer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static initializer" Watch "Static initializer" New topic
Author

Static initializer

lydia westland
Ranch Hand

Joined: Feb 24, 2002
Posts: 72
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


Lydia<br />~~~~~~~~~~~~<br />I love Italy team.
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
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.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
lydia westland
Ranch Hand

Joined: Feb 24, 2002
Posts: 72
Thank you so much for your clarification.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static initializer