I knew that Static variables are created and initialized only one time I.e when the class is loaded and not per object.
In the code given below what I am trying to do is: I declared an int variable "a" as static in class A and assigned it a value of 5. When the main is executed I changed its value to 6 and made the program to loop infinitely. So currently "a" value is 6.
Now what I tried to do is I tried to access this variable from other class class B when class A is still looping and I expected that 6 should be printed when I ran class B (because by the time I ran class B "a" value is changed to 6) but surprisingly it still gave me 5.
Why is this happening even though I declared "a" as static? Unable to figure out what's wrong with this approach.
class A{
static int a=5;
public static void main(String args[]){
System.out.println(A.a+"");
a=6;
while(true){
}
}
}
class B{
public static void main(String args[]){
System.out.println(A.a+"");
}
}
A.mainandB.main. You'd have to use threads within the same process to demonstrate what you expect to see.