why we use static keyword in java like public static void main(String s[])
The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this: public class JavaClass{ protected JavaClass(int x){} public void main(String[] args){ } } Should the JVM call new JavaClass(int)? What should it pass for x? If not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called. There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why main is static. I have no idea why main is always marked public though. Answer credits : http://stackoverflow.com/questions/146576/why-is-the-java-main-method-static
if you know how to make your own secondary classes - using the static keyword in a field variable declaration will make it 'object independent', meaning that all instances of that class (objects that you make which reference that class) will all reference the same static field. (so if you change the static field in one object, it will also change the same field in every other object that references the class) Without the static key word in the field variable declaration, each object you create that references that class will store the field variables separate from one another, (so changing the field in once object that references the class will not influence the variables of any other objects that reference the class (unless of course the objects reference the same object...)). Also, by using the static keyword in methods in secondary class can be called upon without creating an object by doing (SecondaryClassName.methodName(parameters);) If most of this terminology doesn't make sense - I'd study more about how oop works, what objects are, how classes can relate, then the picture about 'field variables' 'objects' and the likes will become much clearer.
Those are some of the effects & practical uses of 'static' that I mentioned; though I can't say that I know a lot about it.
Join our real-time social learning platform and learn together with your friends!