Java Question about Static [closed]
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?
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"
It returns null World
because the text
variable is initialized two times, the first time it's "Hello" and the second time it's null.
IF you move your text
variable declaration before the static init you will get Hello World
.
The answer should be "null World".
Java Initializers are defined to execute in the same order they appear in the source code, so your initialization block will run before you assign null to text.
pro tip against such bugs: Make your static variables final, or don't use static variables at all.
精彩评论