Hello everyone, this week I am going to go over one of the most important concepts in Java, the main method. The main method in itself is pretty easy to understand as it is the part that runs the program but there are components to it most early programmers don’t take the time to learn.
Lets start by taking a look at the syntax of the method:
Public: The method must be public so it is accessible. If the method is marked as private, protected, or default the JVM will not be able to locate it.
Static: The static keyword allows methods to be called without instantiating an object first. We don’t want to be required to create an object to run the main method.
Void: The main method doesn’t return anything so we use void as the return type.
Main(): This is the default signature for the JVM and is used to execute a program.
String args []: This is a string array of command line arguments that are passed to the main method. If this is left out of the parameters the JVM will not be able to locate the main method because it looks for a method with a string array.
What is a command line argument?
$ java myProgram arg1 arg2 arg3
You can then use these arguments from the array in your main method if needed.
public class Example {
public static void main(String[] args) {
for(String arg: args){
System.out.println(arg);
}
}
}
The last thing I want to touch on is how the main method applies to a process. The main method is a thread in a process that is automatically created by the JVM. Each time a thread is created, the JVM allocates a stack of memory to it. Since additional threads are created from the main thread each additional is considered a child of the main thread which means it must finish execution last. This is because the thread that created another must perform the various shutdowns to safely stop it. For more information on multi-threading please click the link to see my post on it.
That is all for this week. Please leave a like and comment down below if you found it useful. Follow me for more posts like this each week as I work to improve my programming knowledge with you all. Have a great day and happy coding!
Resources:
https://www.javatpoint.com/java-main-method
https://techvidvan.com/tutorials/java-command-line-arguments/