Main Method
So, question is that why we need main method.
Let’s take a real life example.
Suppose, you bought a movie ticket and
entered into Multiplex. Now, How would you know which is your hall to see your
movie. You just see your movie tickets and match all the details from the
details showing in front of halls. Like movie name, timings and hall number and
you entered into that hall and enjoying your movie.
Same like this. A java program also
needs some identification to run it. To achieve this, JVM has a default or
pre-define structure or signature for this. This is below.
public
static void main(String[] args){
}
As we have already learn about all the word
which are use to define the main method. All are keywords and we know behaviors
and purpose of each keyword. Except main, main is nothing but just a unique
name to identify the method.
But now question is this, why we have public static void? Why we don’t have
other modifiers or some other return types.
Let’s study that one by one. As we already
learn that JVM need some identification point from where it will run a java
program. So when the JVM was developed, that time the developer defined that
this is the only method from where a Java program should starts.
We can make some of changes, but we will
learn it later.
Okay, we agree that this is the default
signature. But, why only public static
void? Why not private String main() or something else.
Let’s discuss one by one.
public:
This is a simple answer, if in case developer make it
private and we know the behavior of private keyword. Then, how JVM will access
the main method? That’s why it is public.
static:
When we know that only JVM will going to call main
method, then there is no need to make an object of the class. JVM will call
main method by using class name.
void:
There is no need to return anything by main method.
Because, there is no other method will call after complete processing of main
method. If, it will return something, then who will go to use that value? This
is why main method does not return any value.
main:
main is just a pre-define name which is we have to use to
define main method.
String[]
args: It is an String[] type of argument and args
is a reference of String[] type, which is passed into main method. We will know
more about this later.
No comments:
Post a Comment
Thank you for your comments.