Main method in java classes

Java main method Explained [Easy Examples]

The java main method is a standard method that is used by JVM to start the execution of any Java program. The java main method is referred to as the entry point of the Java application. In this tutorial, we will learn about the java main method. We will see how we can create the java main method and explain its every component in detail.

We will also discuss how we can pass different arguments to the java main methods by taking various examples. Moreover, we will also learn the overloading of the java main method. All in all, this is going to be one of the most informative tutorials about the java main method.

Getting started with Java main method

As we already discussed the java main method is the entry point for any Java application. The main method will subsequently invoke all the other methods required by the program. In this section, we will discuss the syntax and different ways of writing the java main method and will explain each of its components in more detail.

Читайте также:  Меняем цвет шрифта при помощи HTML

Different Java main method syntax

The java main method can be written in many ways depending on the situation. Although they’re not very commonly used, they’re valid signatures. Note that none of those are specific to the main method, they can be used with any Java method but they are also a valid part of the main method.

Syntax-1 to use java main method

Let us see some of those methods here. See the simple syntax of writing the java main method.

public static void main(String[] args) < // statements >

Syntax-2 to use java main method

The above one is the most commonly used syntax of the java main method. Notice that the square brackets are just after the String but they can also be written after args as well. See the syntax below:

public static void main(String args[]) < // statements >

This is a valid declaration of the java main method.

Syntax-3 to use java main method

Another way of writing the main method is to add strictfp with it, which is used for compatibility between processors when working with floating-point values. See the simple syntax below:

public static strictfp void main(String[] args) < // statements >

Syntax-4 to use java main method

Another way to write the java main method is to write the final inside the main method which can be applied on args to prevent the array from being modified. See the simple syntax below:

public static void main(final String[] args) < // statements >

Notice that the above all are valid but not commonly used methods of declaration, the very first one is the most popular one and we will also use that syntax in the rest of our tutorial.

Different ways of using Java main method

Understanding the “public” keyword

The public is a Java keyword that declares a member’s access as public. Public members are visible to all other classes. This means that any other class can access a public field or method. Further, other classes can modify public fields unless the field is declared as final. The main method in java is public so that it can be accessible everywhere and to every object which may desire to use it for launching the application.

Notice that if we will not make the main method public, then there will be no compilation error. But we will get runtime error because matching the main method is not present. Remember that the whole syntax should match to execute the java main method. For example, see the example below:

java main method

Notice that it says the main.java is not executable, that is because our main method is not public.

Understanding the keyword “static”

In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type. This means that only one instance of that static member is created which is shared across all instances of the class. In simple words, static methods are the method that invokes without creating the objects, so we do not need any object to call the main method. If we will not make the main method static we will get the following error. See the example below:

java main method error

Notice that it says the main method is not found and gave us the proper syntax of the main method.

Understanding the keyword “void”

The void keyword specifies that a method should not have a return value. In java, every method should have a return type otherwise we will get an error. The main method’s type is void which means that it is not returning anything. If we create the main method without any return type (void) we will get the following error.

java main method void

Understanding the “string arg[]” in the main method

The java main method can also accept some data from the user. It accepts a group of strings, which is called a string array. It is used to hold the command line arguments in the form of string values. The agrs[] is actually an array name, and it is of String type. It means that it can store a group of strings. Remember, this array can also store a group of numbers but in the form of a string only. Values passed to the main method are called arguments. These arguments are stored into args[] array, so the name args[] is generally used for it.

Later in this tutorial, we will take examples and see how we can pass arguments to the main method.

Simple example of Java main method

Now we are familiar with the terms used in the java main method, we are good to go and create a main method and run it. See the example below which prints out a message.

Источник

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.
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.

Источник

Оцените статью