Wednesday, 3 June 2015

Why main method is public static in Java

Syntax of java main method is:

public static void main(String[] args)
{

}

reason for public static void main are:

public: This is because public access specifier is accessible from any where. i.e. inside or outside of the application. And main method is entry point of a class so it should be accessible from anywhere.

static: As main method is an entry point of Java program, while invoking main method there wont be any object. That's why static is required for main method.
we all know while we want to invoke a method there should be an object or method should be static. As for static method no need of object, using class name we can invoke a static method.

void: Return type of main method is void, because Java is platform independent and if main method return any value then meaning of that value can be different in different system.

String[] args:   String[] args is an array of java.lang.String type.And this is specially used to store values received from console.

We all know that Java only deals with String, because we can store any types of value in string.
Thats the another reason for using String array as argument of main method.

Note that args is just a name you can give any name to this. ex: public static void main(String[] variable) and it will work
for ex: String s="123";
and easily we can convert 123 to no.

No comments:

Post a Comment