Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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){

}
like image 453
Throsby Avatar asked Nov 29 '22 13:11

Throsby


2 Answers

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.
like image 67
Diana E Avatar answered Dec 04 '22 16:12

Diana E


its the entry point for any java program, it does whatever you tell it to do. all you need to do is declare it in one of your source java files and the compiler will find it.

like image 27
Neil Locketz Avatar answered Dec 04 '22 15:12

Neil Locketz