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?
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.
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);
}
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With