Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>static { int a=5; double x=4.1; } </code></pre> <p>The purpose of the above block is make the code inside it execute before the <code>main()</code> method does.</p> <p>Whenever one open's a block in java and declare something inside it, here a static block with variables a and x, become local to that particular block, i.e. a and x can't be accessed outside the static block.</p> <p><br/> For more info on scope and lifetime of variables in java refer to following links:<br/></p> <p><a href="http://www.cs.umd.edu/~clin/MoreJava/Objects/local.html" rel="nofollow">http://www.cs.umd.edu/~clin/MoreJava/Objects/local.html</a><br/> <a href="http://www.c4learn.com/java/java-variable-scope/" rel="nofollow">http://www.c4learn.com/java/java-variable-scope/</a><br/></p> <p>So, the static block in this code is there to just confuse you, it does not have any impact on the execution or result of the program in your case.</p> <p>After the execution of static block, we've moved out of it thus destroying it's local resources, i.e. a and x. Now, according to Java, there doesn't exist any variable named <code>a</code>, a new variable with the same name can be initialized.</p> <p>@ismail - In Java, all code is executed from top-to-bottom order like any other language. Assuming you that all static blocks are executed before <code>main()</code> method is called. So consider a case where you have two static blocks:</p> <pre><code>public class MyClass { static { System.out.println("Static Block 1"); } static { System.out.println("Static Block 2"); } } </code></pre> <p>The output of above code would be <br/> <code>Static Block 1</code><br/> <code>Static Block 2</code></p> <p>Something similar is done by you in the your 1st code. 1. You declared some static instance variables. 2. You created a static block with some local variable and called a function from that block which could manipulate instance variables. 3. Due to the flow of Java, firstly instance variables were created and then they were manipulated by your static block. That's how you received modified output.</p> <p>But in 2nd code, the static instance variables got initialized after the execution of static block, hence you received initial values in the output.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload