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+"");
}
}
The problem you are having is that you are running two different JVM processes. What you should be doing is running each of your “main” methods in its own thread. This way they share (and therefore can modify) the same memory. Here is your example modified to use threads:
Side note: While this example does demonstrate what is expected from the question, there is still a lot of things wrong in terms of writing a correct Java program that uses multiple threads. Do your reasearch.