开发者

Java Question about Static [closed]

开发者 https://www.devze.com 2023-03-17 04:42 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消