Java Question about Static

Today I ran into this error in our code, and it took some time. I found this 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 Test.getTest(); and why?

+7
source share
5 answers

He must print the "zero world." Static initializations are performed in the specified order. If you move the ad above the static block, you should get "Hello World".

+18
source

It returns "null World". The documentation states that static initialization occurs in the order in which it appears in the source code, so if you move your static block down, it will return "Hello World"

+1
source

It returns null World because the text variable is initialized twice, the first time it is β€œHello” and the second time it is null. If you move the declaration of the text variable before the static init, you will get Hello World .

0
source

The answer should be "null World".

0
source

Java initializers are defined to execute in the same order as in the source code, so your initialization block will be run before you assign null text.

pro tell me about such errors: make your static variables final or don't use static variables at all.

0
source

All Articles