"public static void main(String[] args)"
When I first encountered the main method, I remember staring at this block of code, feeling overwhelmed. The words public
, static
, and void
were alien to me, and the structure felt rigid compared to the fluid nature of scripting languages. What did these keywords mean? Why was the method so specific? My mind buzzed with questions and apprehensions. In this blog, I am going to give you a beginner's guide to the main method in Java.
In Java the
main
method is the entry point for any standalone application in Java. It is exactly the point where the execution of the program begins.public class demo { public static void main(String[] args){ // code here } }
public
: The main method is declared public because it needs to be accessible by the Java Virtual Machine (JVM) to run your program.
static
: This means that the method belongs to the class, not instances of it. This is required because the main method must be called by the Java runtime without having to instantiate the class.
void
: This means that the method does not return any value.
main
: This is the name of the method. It’s a special method name recognized by the Java runtime as the entry point of the application.
String[] args
: This is an array of Strings. It represents the command-line arguments passed to the program. If no arguments are passed, it's an empty array.
String
represents that the array is of type string.args
represent the name of the array.
Following are the code examples of how command line arguments are passed:
public class demo {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
Compiling:
javac demo.java
Running:
java demo arg1 arg2 arg3
Output:
Number of arguments: 3
Argument 0: arg1
Argument 1: arg2
Argument 2: arg3
Conclusion
Understanding the main
method in Java is crucial for any aspiring Java developer. While its structure might seem daunting at first, breaking down each part reveals its simplicity and power.
Happy coding!!!
Subscribe to my newsletter
Read articles from Vivan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Vivan Kumar
Vivan Kumar
Tech Enthusiast