Want to master Java the easy way?
Subscribe to Ram N Java for simple, beginner-friendly core Java tutorials, code walkthroughs, and practical guides.
Subscribe NowUnderstanding the Main Method in Java
In Java, every standalone application needs an entry point where execution begins. That entry point is the main method. Without it, the Java Virtual Machine (JVM) does not know where to start running your program.
Breaking Down the Method Signature
The standard signature looks like this:
Let's understand what each keyword represents:
- public: An access modifier that lets the JVM invoke this method from outside the class.
- static: Allows the JVM to call the method directly without needing to create an object of the class first.
- void: Indicates that the method doesn't return any value after execution finishes.
- main: The exact name that the JVM looks for to begin program execution.
- String[] args: An array of strings used to pass command-line arguments to your application at runtime.
Complete Example: Reading Command-Line Arguments
Here is an example demonstrating how your program receives and iterates through command-line inputs:
public class MyApp {
public static void main(String[] args) {
System.out.println("Argument count: " + args.length);
if (args.length == 0) {
System.out.println("No arguments passed");
} else {
for (String arg : args) {
System.out.println("Argument: " + arg);
}
}
}
}
Running with Arguments via Command Prompt
To compile and run this code with values passed to String[] args, follow these terminal commands:
java MyApp Peter John Julie Ram
The console will output the count along with each argument printed on a new line:
Argument: Peter
Argument: John
Argument: Julie
Argument: Ram
Recommended Java Tutorials From Our Channel
Level up your Java skills with these related beginner tutorials:
Click here to watch in Youtube :
https://www.youtube.com/watch?v=IRnfSsyKHyA&list=UUhwKlOVR041tngjerWxVccw
MyApp.java








No comments:
Post a Comment