Professional Documents
Culture Documents
Static variable in Java is variable which belongs to the class and initialized only
once at the start of the execution.
A static variable is common to all the instances (or objects) of the class
because it is a class level variable. In other words you can say that only a
single copy of static variable is created and shared among all the instances of
the class. Memory allocation for such variables only happens once when the
class is loaded in the memory.
Like variables we can have static block, static method and static class, to read
about them refer:
Syntax :
<class-name>.<variable-name>
Age is: 30
Static variable initialization
1. Static variables are initialized when class is loaded.
2. Static variables are initialized before any object of that class is created.
3. Static variables are initialized before any static method of the class
executes.
Key points:
final variable always needs initialization, if you don’t initialize it would throw a
compilation error. have a look at below example-
Purpose
The static keyword in Java is mainly used for memory management. The
static keyword in Java is used to share the same variable or method of a
given class. The users can apply static keywords with variables, methods,
blocks, and nested classes. The static keyword belongs to the class than an
instance of the class. The static keyword is used for a constant variable or a
method that is the same for every instance of a class.
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
Output : from m1
Another Example of static block and variable
class Test
{
// static variable
static int a = 10;
static int b;
// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}
Syntax :
<class-name>.<method-name>
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object
created.
Student(){
//Constructor incrementing static variable b
b++;
}
Step 2) Save & Compile the code. Run the code as, java Demo.
Following diagram shows, how reference variables & objects are created and
static variables are accessed by the different instances.
Step 4) It is possible to access a static variable from outside the class using the
syntax ClassName.Variable_Name. Uncomment line # 7 & 8 . Save , Compile &
Run . Observe the output.
Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2
Value of a = 0
Value of b = 3
Step 5) Uncomment line 25,26 & 27 . Save , Compile & Run.
Step 6) Error = ? This is because it is not possible to access instance variable "a"
from java static class method "increment".
A static block helps to initialize the static data members, just like
constructors help to initialize instance members
}
}
Value of a = 10
Value of b = 20