How is the control flow? O/p is 20 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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)

30th May 2021, 9:56 AM
Harshanand Raykar
Harshanand Raykar - avatar
3 Answers
+ 2
Because you have reinitialised I with 20
30th May 2021, 10:00 AM
Atul [Inactive]
+ 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; }
30th May 2021, 10:03 AM
A͢J
A͢J - avatar
+ 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.
30th May 2021, 11:04 AM
Soumik
Soumik - avatar