Are variables declared inside a static block accessible anywhere else? What "kind" of member are they(ie., are they static member, too?)
Asked
Active
Viewed 1.1k times
4 Answers
14
Generally programmers don't need to declare any variables inside static blocks, usually this is only for ensuring initialization of static variables for use by all instances of class (depending on scope of static variable).
Variables declared inside a static block will be local to that block just like methods and constructors variables.
-
"Generally programmers don't need to declare any variables inside static blocks" >> Why not? If you need temporary objects to hold data, you will have variables in static block. Think of a scenario when you need to instantiate a static field after doing arithmetic and want to make code readable `static float radius; static float area; static { final float PI = 3.14f; area = (float) (PI * Math.pow(radius, 2)); }` – realPK Jul 02 '16 at 20:08
10
Variables declared inside a block are accessible only inside of that block. Static or no.
Variables declared inside a static method are static. They can only access other static variables or global variables.

kevingreen
- 1,541
- 2
- 18
- 40
-
But unlike C/C++'s local variables, those variables don't really "go out of scope" after the the block executes, right? – One Two Three Mar 30 '12 at 21:20
-
2The scope of variables in a block is the block. After it executes, you have no way of accessing these variables. That's what it means for variables to go out of scope. A static block only executes once so there is no way you could re-enter it either. Typically you use a static block to initialize static fields in the class when the class is loaded and before any constructors run. Static fields have the scope that you give them: public, package protected, protected, private. – Jilles van Gurp Mar 31 '12 at 09:23
0
No, not visible outside the block. They act like local variables -- think of a static block as an anonymous function that gets called at class initialization. They are not static members.

Sean Owen
- 66,182
- 23
- 141
- 173