Why main method is declared as static in java?

Why main method is declared as static in java?

As you know in simple java program, we declared the main method as following way

public static void main(String args[])

here the method name is main.

By using java javafilename command, JVM loads the java class into the memory and looks for the main class in the java file.

if main method is not found, it throws NoClassFoundError exception.
if main method is found, it will start the java exectuion code process.

if you want to access the any method, we can use method name with object (like object.method()),
For main method, we are declaring the method as static, means JVM can access the main method directly using the direct class name.That's why for being main method declared as static, object creation is not created.

Void in main method returns nothing.

public keyword means, any other outside all classes can be accessed.

Strings Args[]:- arguments are command line arguments for the java class. we can set arguments throug command line as part of java tool to send the some arguments while executing java program.

usage :- java javafilename argument1 argument2

arguments1,argument2 are available in string args[], once execution starts with the above command.

Hope you understand the basic usage of main method.

Please feel free to comment if you like this post, if you  have any questions.

1 comment:

  1. I am a fresher in java and this site has some very helpful pack of articles! Thanks and please keep updating! Sample Statements


Note: only a member of this blog may post a comment.