Ask your own question, for FREE!
Computer Science 15 Online
OpenStudy (anonymous):

Why is so that a program in JAVA also runs with static block only without any main ??

OpenStudy (anonymous):

You want to know if you always need the main() method?

OpenStudy (anonymous):

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.

OpenStudy (anonymous):

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 ...

OpenStudy (anonymous):

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.

OpenStudy (anonymous):

hmmmmm

OpenStudy (anonymous):

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); } }

OpenStudy (anonymous):

public class TestTwo { static { Test test1 = new Test(); Test test2 = new Test(); Test test3 = new Test(); } }

OpenStudy (anonymous):

output after execution is: ~/D/javaTest> java TestTwo Program without Main

OpenStudy (anonymous):

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.

OpenStudy (anonymous):

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.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!