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.
Firstly it should be public static void main(String[] args){...}
.
It must be public
Take a look at The main method
The JVM will look for this method signature when it runs you class...
java helloWorld.HelloWorld
It represents the entry point for your application. You should put all the required initialization code here that is required to get your application running.
The following is a simple example (which can be executed with the command from above)
package helloWorld;
public class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
void
means the method returns no value. String[] args
represents a string of arguments in an Array type that are passed to the program. main
is the single point of entry in to most Java programs.
Glossing over why it should be public static void...
(You wouldn't build a door without a doorknob), methods (equivalent of functions (or subs) in other languages) in Java have a return type. It just so happens that the main
method in Java has to return void. In C or C++, the main method can return
an int
and usually this indicates the code status of the finished program. An int
value of 0
is the standard for a successful completion.
To get the same effect in Java, we use System.exit(intValue)
String[] args
is a string array of arguments, passed to the main function, usually for specific application use. Usually these are used to modify a default behavior or for flags used in short command line executable applications.
main
just means to the JVM, start here! Same name in C and C++ (and probably more).
You should have a main class and a main method. And if you want to find something in the console, you need have one output command at least in the method, like :
System.out.println("Hello World!");
This makes the code running lively.
when you execute your class, anything in the main method runs.
Breaking this down, point-by-point, for the general case:
main()
method;main
executes in order until the end of main
is reached -- this is when your program terminates;static
mean? static
means that you don't have to instantiate a class to call the method;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]
;public
means that the method can be called by any object.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.