Showing posts with label static. Show all posts
Showing posts with label static. Show all posts

Friday, July 18, 2014

Why file name is same as class name containing main method in java ?

Whenever any member is declared as static, it can be used before any of its object is created, just by using class name. Hence static members are used just by using class name. When JVM calls main(), it does not have any instance of class having main() method. So this main() method is called as classname.main().

JVM needs classname to call main() method. How does JVM know what is your classname ?. When java program is compiled as javac filename.java, (filename is same as class name containing main() method) JVM knows your classname using which it calls main().

So file name is same as class name containing main method in java.

Tuesday, July 15, 2014

Why main method is public static void in java

HelloWorld.java is a sample program which contains main method.
To Compile: javac HelloWorld.java
To Execute: java HelloWorld

Lets see what is meaning of public static and void keyword in main() declaration

·         public: The main method is called by JVM when we execute “Java HelloWorld”. But since the JVM is out of scope of main method of the class HelloWorld. to make it accessible by JVM, so main method is public in java.

·         static: static keyword allows us to access members without creating object of that class with the help of class name. When JVM calls main method, it does not have any instance of the class having main method. JVM calls main method internally using class name like HelloWorld.main().So main method is static in java.

·       void: when any method does not returns any value its return type must be void. As main method does not return any value, so main method is void in java.