2

As mentioned in the below link Link

Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
A single copy to be shared by all instances of the class.

But i am able to change the value of static variable

class Test {
  static int a =10;
  public static void main(String args[])
  {
    a=20;
    System.out.println("rest of the code...");
    Test1 t= new Test1();
    t.m();
  }
}

public class Test1 {
    void m () 
     {
         System.out.println(Test.a);
     }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Rahul
  • 163
  • 3
  • 12

2 Answers2

1

The definition means that the variable will be initialized only once in a context of the class definition. Id est, for the class Test in your example it will be initialized only once no matter the number of objects you instantiate for this class.

Take also into account that initialization is not the same as changing the value of the variable later.

To ilustrate your question in comments:

class Test {
    public static long staticAtr = System.currentTimeMillis();
    public long nonStaticAtr = System.currentTimeMillis();

    public static void main(String[] args) {

        Test t1 = new Test();
        Thread.sleep(100);
        Test t2 = new Test();
        System.out.println(t1.staticAtr);
        System.out.println(t1.nonStaticAtr);
        System.out.println(t2.staticAtr);
        System.out.println(t2.nonStaticAtr);
}

t1 and t2 show the same staticAtr that was initialized only once at the start of the execution, while the nonStaticAtr of t1 and t2 where initialized once per instantiation and have therefor different values.

Paco Abato
  • 3,920
  • 4
  • 31
  • 54
0

What is meant by the quoted rule is that when you create instance A of class Test and this initialized member a with 10. If you now change the value of a in A to .e.g 12, the next created class, as well as all previous instances, will see a having a value of 12.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
CannedMoose
  • 509
  • 1
  • 10
  • 18