16

Are variables declared inside a static block accessible anywhere else? What "kind" of member are they(ie., are they static member, too?)

4 Answers 4

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.

JDK Docs

Sign up to request clarification or add additional context in comments.

1 Comment

"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)); }
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.

2 Comments

But unlike C/C++'s local variables, those variables don't really "go out of scope" after the the block executes, right?
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.
4

they are like method variables. Only accessible in the block scope.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.