I came across this bug in our code today and it took a while to figure. I found it interesting so I decided to share it. Here is a simplified version of the problem:
public class Test {
static
{
text = "Hello";
}
public static String getTest() {
return text + " World";
}
private static String text = null;
}
Guess what Test.getTest();
returns & why?
2. Static Block. Static initializer block or static initialization block, or static clause are some other names for the static block. Static block code executes only once during the class loading.
Static blocks in Java are executed automatically when the class is loaded in memory. Static blocks are executed before the main() method. Static blocks are executed only once as the class file is loaded to memory. A class can have any number of static initialization blocks.
Code that relies on static objects can't be easily unit tested, and statics can't be easily mocked (usually). If you use statics, it is not possible to swap the implementation of the class out in order to test higher level components.
Static methods Methods declared as static have several restrictions: They can only directly call other static methods. They can only directly access static data. They cannot refer to this or super in any way.
It should print "null world". Static initializations are done in the order listed. If you move the declaration higher than the static block you should get "Hello World".
It returns "null World" The documentation states that static initialization happens in the order it appears in the source code, so if you move your static block down to the bottom, it will return "Hello World"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With