Why is this static Java field empty?

public class StaticTest {

    private static String a;
    private static String b = "this is " + a;

    public static void main(String[] args) {
        a = "test";

        System.out.println(b); // prints "this is null"
    }

}

I am confused in the meaning b. I think the result should be "this is a test", but the result is "this is null". Why?

+6
source share
6 answers

Others explained why it works the way it is done.

However, there are ways to calculate a value when you reference it.

private static String a;
private static Supplier<String> bSupplier = ()->"this is " + a;

public static void main(String[] args){
    a = "test";
    System.out.println(bSupplier.get()); //Prints "this is a test"
}

When you call bSupplier.get(), the value is computed. If you change the value aand call it again, the value will display the new value.

This is not something you need to do often, but it is good to know.

+6
source

You add String a to string b, but string a is not defined yet. You must add it to line b after you define it.

private static String a = "test";
private static String b = "this is a " + a;
public static void main(String [] args){
  System.out.println(b);
}
+4

b, . . ?

.
, , , .

b .
b getB(), String a :

public class StaticTest {

    private static String a;

    public static void main(String[] args) {
        a = "test";    
        System.out.println(getB());
    }

    private static String getB(){
       return "this is " + a;    
    } 
}

PS: , Java 8.

+3

private static String a;
private static String b = "this is " + a;

a null. String b

this is null

a b. .

private String a = "test";
private String b = "this is " + a;
+2

, , , , , a null b "this is null", , a "test".

Java,

private static String b = "this is" + a;

"this is" a. a , b , b a, , .

+1

classloader JVM,

1.)

2.) ( , .. (a.) , (b.) , (c.) )

3.)

, (link) classloader ( ) ( ), - null.

Now, during the initialization phase, static variables are assigned their actual value, and a- null. Because the method mainwill be launched after this step.

Thus, a avalue is assigned inside the main one "test", and is balready assigned by the class loader during initialization, when ait is NULL, which is why the reason String bhas a strange output.

+1
source

Source: https://habr.com/ru/post/1016571/


All Articles