+ 1
How is the control flow? O/p is 20
class Shyam { static int i = 10: static { i = 20; } } class ShyamSundar { p s v M() { S.o.p(Shyam.i)
3 Respostas
+ 2
Because you have reinitialised I with 20
+ 1
Harshanand Raykar
Here we have one static variable with 10 and we have static block where we have re-assigned value 20.
As we know that static stores in memory first time JVM start.
We can access static data just by using Class so here result is 20
But you if do like this then result will be 10
class Shyam
{
static
{
i = 20;
}
static int i = 10;
}
+ 1
Static block is mainly used for the static initializations of a class. The block consists of a set of statements which are executed before the execution of the main method. This is due to the fact that the class has to be loaded into the main memory before its usage, and static block is executed during the loading of the class. On defining a number of static blocks in a program, the blocks execute from the top to the bottom. Static blocks are executed before constructors.
In your code, although you've declared i = 10, the static block executes before the main method and value is set to 20.