Why is so that a program in JAVA also runs with static block only without any main ??
You want to know if you always need the main() method?
Because Java is Object-Oriented, everything is an object. Static methods allow you to use a block of code without instantiating an instance of that class.
public class WithoutMain { static { System.out.println("Program without Main"); System.exit(0); } } why this dont need any main method as the only way to run without main is making applet ...
All right, this is a interesting question. So, labeling something as static within a class makes that item part of the class itself and not the object. For instance, if you were to give a static variable 'count' which you use to keep track of the number of cars you've created, that value would sort of exist outside of each Car object created.
hmmmmm
For your static block, if you were to instantiate more than one 'WithoutMain' class object, you would only see the code in the static block printed once. public class Test { public Test() { } static { System.out.println("Program without Main"); System.exit(0); } }
public class TestTwo { static { Test test1 = new Test(); Test test2 = new Test(); Test test3 = new Test(); } }
output after execution is: ~/D/javaTest> java TestTwo Program without Main
So this does then depend upon the environment in which you are using you Java classes. An applet is made so that it can be used on the web, while non-applets are not.
Thanks, but I feel I may not have given the real answer. I guess this actually is difficult question, I've seen mention that since Java is Object-Oriented that main method is an 'entry point' into a class.
Join our real-time social learning platform and learn together with your friends!