The following example defines 2 static variables. Variable 1 (myBoolean1) is defined above the MySingletonExample (instance) variable.
Variable 2 (myBoolean2) is defined below the MySingletonExample (instance) variable.
Both variables are set to true but only 1 variable (myBoolean1) shows the proper value when displayed.
public class MySingletonExample
{
//static volatile boolean myBoolean1 = false;
static boolean myBoolean1 = false;
private static volatile MySingletonExample instance = new MySingletonExample();
//static volatile boolean myBoolean2 = false;
static boolean myBoolean2 = false;
private MySingletonExample()
{
myBoolean1 = true;
myBoolean2 = true;
}
protected static MySingletonExample getInstance()
{
System.out.println("myBoolean1 = " + myBoolean1);
System.out.println("myBoolean2 = " + myBoolean2);
return instance;
}
public static void main(String[] args)
{
MySingletonExample.getInstance();
System.out.println("---------------------------");
MySingletonExample.getInstance();
}
}
When executed, this is the output.
myBoolean1 = true
myBoolean2 = false
myBoolean1 = true
myBoolean2 = false
Why doesn't myBoolean2 return true instead of false like myBoolean1?
The only different is the placement. Is there a "rule" when working with static variables?