This week's book giveaways are in the Scala and Android forums.
We're giving away four copies each of Machine Learning Systems: Designs that scale and Xamarin in Action: Creating native cross-platform mobile apps and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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.
 
You totally ruined the moon. You're gonna hafta pay for that you know. This tiny ad agrees:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!