- A static variable is a variable which is initialized only once at the start of execution.
- Static variable belongs to the class and not to the object of the class.
- Static variables should be initialized before the initialization of instance variables.
Like this :
public static int a = 20;
Here, we initialized the value of 'a' as 20 directly.
But what if we want to initialize that static variable when a certain condition is met?
For example, I want to initialize 'a' as 20 when the other value 'b' is greater than zero. If 'b' is less than zero, I want to initialize 'a' as 30.
How do we do this?
That's where the role of static initialization blocks comes into play.
A Static Initialization Block is a normal block of code enclosed in braces and preceded by the static keyword.
There can be any number of static initialization blocks in a class. They are called in the order in which they are written in the program.
An Example Demonstrating Static Initialization Blocks:
class StaticDemo{
static int a;
static int b;
//Static Initialization Block starts
static{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the value of b: ");
b = scan.nextInt();
if(b >= 0){
a = 20;
}
if(b < 0){
a = 30;
}
}
public static void main(String... args){
System.out.println("Value of a is: "+ a);
}
}
From the above program, we can see that the value of 'a' is 20 when the value of 'b' is greater than or equal to zero. Similarly, the value of 'a' is 30 when the value of 'b' is less than zero.
Comments
Post a Comment