- Java main() Method – public static void main(String[] args)
- Syntax of main() Method
- Java
- 1. Public
- Java
- 2. Static
- Java
- 3. Void
- Java
- 4. main
- Java
- 5. String[] args
- Java
- FAQs on Java main() Method
- Q1. Can the main method be int? If not, why?
- Java
- Java
- Explanation of the above programs:
- Q2. Can we execute a Java program without the main method?
- Q3. Can we declare the main() method without String[] args?
- Lesson: A Closer Look at the «Hello World!» Application
- Source Code Comments
- The HelloWorldApp Class Definition
- The main Method
- Java class public static void main string args
Java main() Method – public static void main(String[] args)
In Java programs, the point from where the program starts its execution or simply the entry point of Java programs is the main() method. Hence, it is one of the most important methods of Java, and having a proper understanding of it is very important.
The Java compiler or JVM looks for the main method when it starts executing a Java program. The signature of the main method needs to be in a specific way for the JVM to recognize that method as its entry point. If we change the signature of the method, the program compiles but does not execute.
The execution of the Java program, the java.exe is called. The Java.exe in turn makes Java Native Interface or JNI calls, and they load the JVM. The java.exe parses the command line, generates a new String array, and invokes the main() method. A daemon thread is attached to the main method, and this thread gets destroyed only when the Java program stops execution.
Syntax of main() Method
The most common in defining the main() method is shown in the below example.
Java
Every word in the public static void main statement has got a meaning in the JVM that is described below:
1. Public
It is an Access modifier, which specifies from where and who can access the method. Making the main() method public makes it globally available. It is made public so that JVM can invoke it from outside the class as it is not present in the current class.
Java
Error: Main method not found in class, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
2. Static
It is a keyword that is when associated with a method, making it a class-related method. The main() method is static so that JVM can invoke it without instantiating the class. This also saves the unnecessary wastage of memory which would have been used by the object declared only for calling the main() method by the JVM.
Java
Error: Main method is not static in class test, please define the main method as: public static void main(String[] args)
3. Void
It is a keyword and is used to specify that a method doesn’t return anything. As the main() method doesn’t return anything, its return type is void. As soon as the main() method terminates, the java program terminates too. Hence, it doesn’t make any sense to return from the main() method as JVM can’t do anything with the return value of it.
Java
Error: Main method not found in class, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
4. main
It is the name of the Java main method. It is the identifier that the JVM looks for as the starting point of the java program. It’s not a keyword.
Java
Error: Main method not found in class, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
5. String[] args
It stores Java command-line arguments and is an array of type java.lang.String class. Here, the name of the String array is args but it is not fixed and the user can use any name in place of it.
Java
Apart from the above-mentioned signature of main, you could use public static void main(String args[]) or public static void main(String… args) to call the main function in Java. The main method is called if its formal parameter matches that of an array of Strings.
FAQs on Java main() Method
Q1. Can the main method be int? If not, why?
Java
prg1.java:6: error: missing return statement > ^ 1 error
Java does not return int implicitly, even if we declare the return type of main as int. We will get a compile-time error
Java
Error: Main method must return a value of type void in class GeeksforGeeks, please define the main method as: public static void main(String[] args)
Now, even if we do return 0 or an integer explicitly ourselves, from int main. We get a run time error.
Explanation of the above programs:
The C and C++ programs which return int from main are processes of Operating System. The int value returned from main in C and C++ is exit code or exit status. The exit code of the C or C++ program illustrates, why the program was terminated. Exit code 0 means successful termination. However, the non-zero exit status indicates an error.
For Example exit code 1 depicts Miscellaneous errors, such as “divide by zero”.
The parent process of any child process keeps waiting for the exit status of the child. And after receiving the exit status of the child, cleans up the child process from the process table and free the resources allocated to it. This is why it becomes mandatory for C and C++ programs(which are processes of OS) to pass their exit status from the main explicitly or implicitly.
However, the Java program runs as a ‘main thread’ in JVM. The Java program is not even a process of Operating System directly. There is no direct interaction between the Java program and Operating System. There is no direct allocation of resources to the Java program directly, or the Java program does not occupy any place in the process table. Whom should it return an exit status to, then? This is why the main method of Java is designed not to return an int or exit status.
But JVM is a process of an operating system, and JVM can be terminated with a certain exit status. With help of java.lang.Runtime.exit(int status) or System.exit(int status).
Q2. Can we execute a Java program without the main method?
Yes, we can execute a Java program without a main method by using a static block.
A static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by ClassLoader, It is also known as a static initialization block, and it goes into the stack memory.
Q3. Can we declare the main() method without String[] args?
Yes, we can declare the main() method without String[] args. Although it will generate an error message if we directly try to execute the main method inside the driver class as done in the below example.
Lesson: A Closer Look at the «Hello World!» Application
Now that you’ve seen the «Hello World!» application (and perhaps even compiled and run it), you might be wondering how it works. Here again is its code:
The «Hello World!» application consists of three primary components: source code comments, the HelloWorldApp class definition, and the main method. The following explanation will provide you with a basic understanding of the code, but the deeper implications will only become apparent after you’ve finished reading the rest of the tutorial.
Source Code Comments
/** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp < public static void main(String[] args) < System.out.println("Hello World!"); // Display the string. > >
Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments:
/* text */ The compiler ignores everything from /* to */ . /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */ . The javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc , see the Javadoc™ tool documentation . // text The compiler ignores everything from // to the end of the line.
The HelloWorldApp Class Definition
/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp public static void main(String[] args) < System.out.println("Hello World!"); // Display the string. >>
As shown above, the most basic form of a class definition is:
The keyword class begins the class definition for a class named name , and the code for each class appears between the opening and closing curly braces marked in bold above. Chapter 2 provides an overview of classes in general, and Chapter 4 discusses classes in detail. For now it is enough to know that every application begins with a class definition.
The main Method
/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp < public static void main(String[] args) System.out.println("Hello World!"); //Display the string. > >
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order ( public static or static public ), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose «args» or «argv».
The main method is similar to the main function in C and C++; it’s the entry point for your application and will subsequently invoke all the other methods required by your program.
The main method accepts a single argument: an array of elements of type String .
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application. For example:
Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:
The «Hello World!» application ignores its command-line arguments, but you should be aware of the fact that such arguments do exist.
System.out.println("Hello World!");
uses the System class from the core library to print the «Hello World!» message to standard output. Portions of this library (also known as the «Application Programming Interface», or «API») will be discussed throughout the remainder of the tutorial.
Java class public static void main string args
Она означает, что в строке 1 файла MyApp.java объявляется публичный класс с именем MyFirstApp, а значит и находиться он должен в файле с таким же именем.
2) Теперь нарушим еще одно правило, написав имя класса и файла с маленькой буквы, назвав их myFirstApp. Запустив программу, видим, что отобразилось сообщение Write once, run anywhere.
Можно сделать вывод, что писать имя файла и класса с большой буквы является лишь договоренностью всех программистов друг с другом. Это сделано для того, чтобы в коде не путать имена переменных (начинаются с маленькой буквы. О них мы поговорим в другой статье) с именами классов.
3) Попробуем изменить имя метода main, например, на Main. Запустив программу, увидим следующую ошибку:
JVM не смогла запустить программу т. к. не нашла метод main (с маленькой буквы). О чем и свидетельствует ошибка Error: main method not found.
4) Вернем методу его первоначальное имя, но удалим слова public static и снова запустим. Возникнет та же самая ошибка, что и в предыдущем пункте, связанная с тем, что при запуске программы не был найден метод main, записанный по всем правилам.
Самостоятельно попробуйте удалять разные части программы и смотреть, какие при этом будут возникать ошибки.