underscore
underscore

Reputation: 61

JAVA, public static variables initialization

/* ---------------------- classes --------------- */

public class A {
  public static String str = "compile";
      public A() {
  }
}

public class B {
  public static String str = A.str;

  public B() {
  }
}

/* ----------------------------------------------- */

/* ------------ main class --------------------- */

public class C {

  public static void main(String[] args) {
    A.str = "runtime";
    A a = new A();
    B b = new B();

    // comment at the first, and comment this out next time
    //A.str = "runtime2";

    System.out.println(A.str);
    System.out.println(a.str);
    System.out.println(B.str);
    System.out.println(b.str);
  }
}

/* --------------------------------------------- */

results is like this....

  1. with comment : runtime runtime runtime runtime

  2. without comment : runtime2 runtime2 runtime runtime

I understand in A's case, but i don't in B's case. Would you please explain about this?

Upvotes: 1

Views: 266

Answers (2)

A4L
A4L

Reputation: 17595

Classes in java are loaded and initialized when they are accessed for the first time.

So here what happens in your main method:

  1. you write A.str = ... : at this point (before the assignment happens) the class A is loaded and initialized, the variable str holds the string "compile"
  2. after A.str = "runtime"; the old value "compile" is overriden
  3. A a = new A(); does not change anything
  4. with B b = new B(); the class B get loaded too and initialized. the value of B.str get the actual value of A.str

this is what explains the first output: runtime all the way

now you uncoment A.str = "runtime2";, only the variable str in class A is changed. B.str remain on runtime.

this is what explains the second output.

Upvotes: 1

rgettman
rgettman

Reputation: 178263

At the first appearance of A in your code, A.str gets initialized to "compile", but then it gets immediately overwritten with "runtime".

Then you declare your a and b instances. But this is where class B is referenced for the first time, so it gets initialized here to A.str, which is currently "runtime".

In your commented code,

//A.str = "runtime2";

This would change only A.str; B.str would still refer to "runtime". And it is possible to access a static variable with either the classname A.str or an instance a.str.

Upvotes: 2

Related Questions