Static Keyword In Java
While writing java code we are using static keywords. Yes, it is required. But, it is more confusing for beginners. they get confused about static keywords.
Here, I will show how to use, and when to use i.e in and out of static keywords.
Consider that we are having instance variables in a class and we created an object of the same class. During object, creation memory got allocated to instance variables. I mean whenever an object gets created memory gets allocated to an instance variable inside object.
instance variable we create as follows,
int number1 = 10;
int number2 = 20;
But in the case of static variables at the time of class loading, only memory gets allocated i.e at the time of class loading only static variables and the block will get executed.
During class loading in JVM, at preparation stage memory gets allocated to static variables in the heap and JVM will provide default values.
we create a static variable by providing static keywords to the variable.
static int number1;
static int number2;
So, the memory gets allocated to static variables first before creating an object i.e memory gets allocated to static variables at once.
Here we can use a static block also to initialize the static variables.
we can create a static block as follows,
static{
System. out.println("Hello, I am inside static block")
number1 = 10;
number2 = 20;
}
The very interesting thing about a static block is, before executing the main method static block will get executed.
When to use static keywords?
As discussed above, when we write static variables, memory gets allocated during class loading only, hence memory is allocated at once.
So, we can use static keywords, whenever we are supposed to share a common copy of data among all the objects.
Note:-
static variables we can access in non- static block and method
Non-static methods cannot be accessed inside a static block or static method.
If we are having static variables and static blocks and static methods,main method in our code , then very first static variables will get executed then static block and then static method.
If we are having multiple static methods, then priority will be given to the main method.