Just like in C++, each executable Java project should have a main method. This isn’t just the “main” method that is run, but an actual method called main()
.
If you look at the previous page for creating a file, we can start from there.
This will be a little different from the C++ main method, and it does require some very specific syntax, which we’ll go over step by step.
public class Sample1 {
public static void main(String args[]) {
// the main method
}
}
Accessor
All methods in Java require an accessor, either public, package, protected, or private. If you leave it off, it will assume package. However, for Java, the main method must be public
, so that it can be called by the JVM (Java Virtual Machine) which is an outside source.
Notice that it is referred to as a method, instead of a function, because it is within a class definition.
Static
static
is a keyword in Java that means the variable, or method in this case, can exist without a class being created into an object. Since we are starting off, and the JVM is needing to call a method first, it needs to call a static method since no object can be created at this point.
This keyword is optional in most methods, and most methods will not be using it. However, this is the exception.
main()
main()
is the method name that the JVM is looking for. As such, it should exist uniquely within a project in most cases, and must be unique within a given class, so the JVM knows exactly which method to call. This is just like you’d find in C/C++.
Parameter List
Since you cannot overload the main method, you need to know how to handle potential parameters. the easiest way is to store them as an array of String objects. Now you can loop though them, finding the parameters that you will need to work with and setting up the initial settings in your runtime code.
We’re not looking to use parameters in this example, but we still have to include them, just in case. Missing them will cause errors.
Method Body
Just as with C/C++, your body will be contained with a set of braces {}
. Anything you need to call or run, will be between the braces alone.
Java’s main Method was originally found on Access 2 Learn
3 Comments
Comments are closed.