This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Exception in thread "main" java.lang.StackOverflowError at java.security.AccessControlContext.optimize(Unknown Source)
at java.security.AccessController.getContext(Unknown Source)
at java.lang.Thread.init(Unknown Source)
at java.lang.Thread.<init>(Unknown Source)
Now if At Line 1 where I have instantiated an object of Class, if the same program is run with below statement,
public static ThreadEx2 ex = new ThreadEx2();
No such error is observed. Can somebody help me on solving on this.
[Edit - added code tags - see UseCodeTags for details]
In your original version, you have an initialisation statement within ThreadEx2 creating a new ThreadEx2. So every time you create a ThreadEx2 it creates another ThreadEx2 which creates another ThreadEx2 which creates another ThreadEx2......this continues until it runs out of space to store the "stack" of calls in, and you get a StackOverflowError.
In your second version it's static, so there's only one instance for the class. So you create a ThreadEx2 when the class is loaded, and then stop. The only others ones created are the ones you create explicitly after that.