Why the public static void main string args method?
public static void main is the famous method found in all our Java programs, but it is also implemented in other object-oriented languages.Example:
public class MainTest {
public static void main (String[] args) {
String str = "Hello everyone";
System.out.println(str);
}
}
Hello everyone
What does the main of a java program mean?
The main is the method that is found in the main class in the root of the execution stack. In the Java programming language, each application or program must contain the method main:public static void main(String[] args)
- public indicates that the main is accessible from other classes;
- static allows the method to be invoked without instantiating the object of the class;
- void means a procedure that does not have a return type.
The main method accepts a single argument as an array of strings String.
String[] args
This array is the mechanism for the system to pass the information to your application. Each String is a command line. For example:
java main arg1 arg2 arg3
Beginner programmers and even most applications don't do this, it's just to tell you how to define arguments and pass them through the arrayargs. So, String[] args is optional.
Example:
public class MainTest {You won't get any results in the Eclipse console or Netbeans because you didn't pass the arguments. As I said, the execution is done on the command line. Type cmd in the Start menu search box:
public static void main (String[] args) {
int i=1;
for (String s: args) {
System.out.println("args["+i+"] : "+s);
i++;
}
}
}
The first thing to do is to access the location of the JDK compiler with the cd command, then copy the class MainTest.java in the JDK file. Next, the compilation step with javac and at the end the execution java MainTest hello world 2015. It's simple, we passed the hello world 2015 arguments and printed them.
How to do it directly in Eclipse?
It's simpler:
- Click File --> Properties --> Run/Debug Settings and click Edit in the right panel;
- In the Edit Configuration window, click on Arguments, where the arguments are populated;
What does 'public static void' mean in Java?
A Closer Look at the "Hello World!" Application
Command-Line Arguments