The code in the following snippet throws java.lang.StackOverflowError.
public class Main
{
private Main m=new Main(""); //This statement causes the exception.
private Main(String s)
{
System.out.println(s);
}
public static void main(String[] args)
{
try
{
Main m1=new Main("The constructor called.");
System.out.println("Successful!");
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
There is no meaning to deliberately write this statement private Main m=new Main(""); inside the class itself but that statement is not ever supposed to be used by any code in the class then how can that statement cause the exception to be thrown?
Each time you call the constructor, you create an instance and thus execute the initializing code
which calls the constructor, etc.
You probably want
in order to keep a singleton.