Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Java static field null?

Tags:

java

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'm confused about b's value. I think the result should be "this is test", but the result is "this is null". Why?

like image 301
acethan Avatar asked Apr 16 '17 11:04

acethan


4 Answers

Others have explained why it works the way it does.

However, there are ways to to have the value calculated 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 calculated. If you change the value of a, and call it again, the value will reflect the new value.

This is not something you should be doing often, but is useful to know.

like image 88
Steven Waterman Avatar answered Oct 20 '22 00:10

Steven Waterman


You add String a to string b but string a is not yet defined.you should add it to string 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);
}
like image 22
Radu Soigan Avatar answered Oct 19 '22 23:10

Radu Soigan


When classloader loads a class into JVM, it does it in three phases

1.) Load

2.) Link (Which is further divided into three steps i.e. (a.) verify, (b.) prepare, (c.) resolve)

3.) Initialize

So during prepare (Link) phase classloader initialize the static variables (not instance) and sets them to their default initial values (not actual value), and for the string it is null.

Now During Initialize phase static variables are assigned their actual value and still a is null. Because main method will be run after this step.

So inside main a is assigned value "test" and b is already assigned by classloader during initialization when a was null, so that is the reason String b has strange output.

like image 24
Pardeep Avatar answered Oct 20 '22 00:10

Pardeep


You did

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

At this point, a was null. Therefore, the String b became

this is null

Now, any changes in a wouldn't reflect on b. Therefore, this result. For the expected result, do

private String a = "test";
private String b = "this is " + a;
like image 24
dumbPotato21 Avatar answered Oct 20 '22 00:10

dumbPotato21