Hi
My understanding is that all static variables and static blocks shall be initialized/executed before anyone accesses the class (static method or object creation). Below code is not working as expected, please help me in understanding where I am wrong.
public class StaticTest
{
private static StaticTest myInstance = new StaticTest();
static
String str = null;
static int i =0;
private StaticTest()
{
try
{
i = 1;
str = "constructor";
}
catch(Exception e){}
}
public static String getData()
{
return i + str;
}
}
Test class:
public class Test
{
public static void main(String[] args)
{
System.out.println(StaticTest.getData());
}
}
Output: "0null"
I was expecting: "1constructor"