Search code examples
javamethodsprogram-entry-point

How does the main method work?


I'm the product of some broken teaching and I need some help. I know that there is this thing called the "main method" in Java and I'm sure other programming languages. I know that you need one to make your code run, but how do you use it to make your run? What does it do and what do you need to have it put in it to make your code run?

I know it should look something like this. But almost nothing more.

static void main(String[] args){

}

Solution

  • Breaking this down, point-by-point, for the general case:

    1. All Java applications begin processing with a main() method;
    2. Each statement in the main executes in order until the end of main is reached -- this is when your program terminates;
    3. What does static mean? static means that you don't have to instantiate a class to call the method;
    4. String[] args is an array of String objects. If you were to run your program on the command line, you could pass in parameters as arguments. These parameters can then be accessed as you would access elements in an array: args[0]...args[n];
    5. public means that the method can be called by any object.