Are variables declared inside a static block accessible anywhere else? What "kind" of member are they(ie., are they static member, too?)
4 Answers
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.
1 Comment
realPK
"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)); }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.
2 Comments
One Two Three
But unlike C/C++'s local variables, those variables don't really "go out of scope" after the the block executes, right?
Jilles van Gurp
The 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.