Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of variables declared inside a static block in java?

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

like image 951
One Two Three Avatar asked Mar 30 '12 20:03

One Two Three


People also ask

What is the scope of static variables in Java?

When an instance variable is declared using the keyword static is known as a static variable. Their scope is class level but visible to the method, constructor, or block that is defined inside the class.

What is variable scope in Java in class in method in static block?

Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can determined at compile time and independent of function call stack. Java programs are organized in the form of classes.

What is the scope of a static variable?

The scope of the static local variable will be the same as the automatic local variables, but its memory will be available throughout the program execution. When the function modifies the value of the static local variable during one function call, then it will remain the same even during the next function call.

What is a static block in Java?

In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block. This is because it is an option for initializing or setting up the class at run-time.


1 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.

JDK Docs

like image 117
AJD301 Avatar answered Oct 06 '22 16:10

AJD301