Java Main Method
A Java program is a sequence of Java instructions that are executed in a certain order. Since the Java instructions are executed in a certain order, a Java program has a start and an end.
To execute your Java program you need to signal to the Java Virtual Machine where to start executing the program. In Java, all instructions (code) have to be located inside a Java class. A class is a way of grouping data and instructions that belong together. Thus, a class may contain both variables and methods. A variable can contain data, and a method groups together a set of operations on data (instructions). Don’t worry if you do not fully understand this yet. It will be explained in more details in later texts.
A Simple Java Class Declaration
Declaring a simple class without any variables, methods or any other instructions, looks like this in Java code:
This Java code needs to be located in a file with the same file name as the class and ending with the file suffix .java . More specifically, the file name has to be MyClass.java . Once the file is located in a file matching its class name and ending with .java , you can compile it with the Java compiler from the Java SDK, or from inside your Java IDE (which is much easier).
It is recommended that you locate your class in a Java package. A Java package is simply a directory in your file system which can contain one or more Java files. Packages can be nested, just like directories can normally. For instance, you could create a package called myjavacode which would correspond to a directory on your hard drive with the name myjavacode .
If you locate a Java class inside a Java package, you have to specify the package name at the top of the Java file. Here is how the class from earlier looks with a package declaration added:
package myjavacode; public class MyClass
Note: The file MyClass.java must now be located in the directory myjavacode and contain the package declaration package myjavacode; . It is not enough that the Java file is located in the correct directory. Nor is it enough to just have the package declaration inside the Java file. Both requirements must be met.
The main() Method
A Java program needs to start its execution somewhere. A Java program starts by executing the main method of some class. You can choose the name of the class to execute, but not the name of the method. The method must always be called main . Here is how the main method declaration looks when located inside the Java class declaration from earlier:
package myjavacode; public class MyClass < public static void main(String[] args) < >>
The three keywords public , static and void have a special meaning. Don’t worry about them right now. Just remember that a main() method declaration needs these three keywords.
After the three keywords you have the method name. To recap, a method is a set of instructions that can be executed as if they were a single operation. By «calling» (executing) a method you execute all the instructions inside that method.
After the method name comes first a left parenthesis, and then a list of parameters. Parameters are variables (data / values) we can pass to the method which may be used by the instructions in the method to customize its behaviour. A main method must always take an array of String objects. You declare an array of String objects like this:
Don’t worry about what a String is, or what an array is. That will be explained in later texts. Also, it doesn’t matter what name you give the parameter. In the main() method example earlier I called the String array parameter args , and in the second example I called it stringArray . You can choose the name freely.
After the method’s parameter list comes first a left curly bracket ( < ), then some empty space, and then a right curly bracket ( >). Inside the curly brackets you locate the Java instructions that are to be executed when the main method is executed. This is also referred to as the method body. In the example above there are no instructions to be executed. The method is empty.
Let us insert a single instruction into the main method body. Here is an example of how that could look:
package myjavacode; public class MyClass < public static void main(String[] args) < System.out.println("Hello World, Java app"); >>
Now the main method contains this single Java instruction:
System.out.println("Hello World, Java Program");
This instruction will print out the text Hello World, Java Program to the console. If you run your Java program from the command line, then you will see the output in the command line console (the textual interface to your computer). If you run your Java program from inside an IDE, the IDE normally catches all output to the console and makes it visible to you somewhere inside the IDE.
Running The main() Method
When you start a Java program you usually do so via the command line (console). You call the java command that comes with the JRE, and tells it what Java class to execute, and what arguments to pass to the main() method. The Java application is then executed inside the JVM (or by the JVM some would claim). Here is a diagram illustrating this:
A command line executing the java command, which in turn executes a Java main program. |
Here is an example command line:
java -cp classes myjavacode.MyClass
The first part of this command is the java command. This command starts up the JVM. In some cases you may have to specify the full path to where the java command is located on your computer (typically inside the bin subdirectory of the Java install dir).
The second and third arguments ( -cp classes ) tells the JVM in what directory the compiled Java classes are located (cp means class path). In this case the compiled Java classes are located in a directory named classes .
The fourth argument is the name of the Java class the JVM is to execute. Notice how the class name also contains the name of the package the class is located in (the «fully qualified class name»).
Passing Arguments to the main() Method
You can pass arguments from the command line to the main() method. This command line shows how:
java -cp classes myjavacode.MyClass Hello World
When the JVM executes the main() method of the myjavacode.MyClass , the String array passed as parameter to the main() method will contain two Strings: «Hello» and «World».
The main() method can access the arguments from the command line like this:
package myjavacode; public class MyClass < public static void main(String[] args) < System.out.println( args[0] ); System.out.println( args[1] ); >>
Notice the references to element 0 and element 1 in the args array ( args[0] and args[1] ). args[0] will contain the String (text) Hello and args[1] will contain the String World .
Compiling and running Java source code is explained in more detail in the text Java Project Overview, Compilation and Execution.
Variables and arrays will be explained in more detail in later texts. Don’t worry if you don’t fully understand them at this point.
The Java Main Class
If only a single Java class in your Java program contains a main() method, then the class containing the main() method is often referred to as the main class.
You can have as many classes as you want in your project with a main() method in. But, the Java Virtual Machine can only be instructed to run one of them at a time. You can still call the other main() methods from inside the main() method the Java Virtual Machine executes (you haven’t seen how yet) and you can also start up multiple virtual machines which each execute a single main() method.
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.
Setting main class in java
Она означает, что в строке 1 файла MyApp.java объявляется публичный класс с именем MyFirstApp, а значит и находиться он должен в файле с таким же именем.
2) Теперь нарушим еще одно правило, написав имя класса и файла с маленькой буквы, назвав их myFirstApp. Запустив программу, видим, что отобразилось сообщение Write once, run anywhere.
Можно сделать вывод, что писать имя файла и класса с большой буквы является лишь договоренностью всех программистов друг с другом. Это сделано для того, чтобы в коде не путать имена переменных (начинаются с маленькой буквы. О них мы поговорим в другой статье) с именами классов.
3) Попробуем изменить имя метода main, например, на Main. Запустив программу, увидим следующую ошибку:
JVM не смогла запустить программу т. к. не нашла метод main (с маленькой буквы). О чем и свидетельствует ошибка Error: main method not found.
4) Вернем методу его первоначальное имя, но удалим слова public static и снова запустим. Возникнет та же самая ошибка, что и в предыдущем пункте, связанная с тем, что при запуске программы не был найден метод main, записанный по всем правилам.
Самостоятельно попробуйте удалять разные части программы и смотреть, какие при этом будут возникать ошибки.