Execute method in main java

Java main() method explained with examples

In this article, we will learn Java main() method in detail. As the name suggest this is the main point of the program, without the main() method the program won’t execute.

What is a main() method in Java?

The main() method is the starting point of the program. JVM starts the execution of program starting from the main() method.

Syntax of main() method:

public static void main(String args[])

public: We have already learned in the access specifier tutorial that public access specifier allows the access of the method outside the program, since we want the JVM to identify the main method and start the execution from it, we want it to be marked “public”. If we use other access modifier like private, default or protected, the JVM wouldn’t recognise the main() method and the program won’t start the execution.

static: The reason the main() method is marked static so that it can be invoked by JVM without the need of creating an object. In order to invoke the normal method, we need to create the object first. However, to invoke the static method we don’t need an object. Learn more about static method here.

Читайте также:  Get random float python

void: This is the return type. The void means that the main() method will not return anything.

main(): This the default signature which is predefined by JVM. When we try to execute a program, the JVM first identifies the main() method and starts the execution from it. As stated above, the name of this method suggests that it is the “main” part of the program.

String args[]: The main method can also accepts string inputs that can be provided at the runtime. These string inputs are also known as command line arguments. These strings inputs are stored in the array args[] of String type.

Can we have main() method defined without String args[] parameter?

If we have a main() method without String args[] in a program, the program will throw no compilation error however we won’t be able to run the program as the JVM looks for the public main method with the String args[] parameter and if it doesn’t find such method, it doesn’t run the program.

Error: Main method not found in class JavaExample, please define the main method as: public static void main(String[] args)

As you can see that the program threw error at runtime.

Java – static block vs main method

As we learned in the previous article, static block is used to initialise the static data members. Let’s run a program with static block and main method (static method) to see in which order they run.

class JavaExample < //static block static < System.out.println("Static Block"); >//static method public static void main(String args[]) < System.out.println("Main Method"); >>

As we can see, the static block executed before the main method.

What if a program doesn’t have a main method?

Let’s write a program without the main method to see whether it runs or not.

Error: Main method not found in class JavaExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

Different ways to write main method in java

The following are the valid ways to write a main method in java:

public static void main(String[] args) //We can interchange static and public static public void main(String[] args) //We can place the square brackets at the different locations public static void main(String[] args) public static void main(String []args)

Overloading of main() method in Java

We can overload the main method in Java. This allows us to have more than one main() method in Java. However the signature of all the overloaded methods must be different. To learn more about overloading, refer this guide: Method overloading in Java.

class JavaExample < public static void main(String args[]) < System.out.println("main method"); main(100); main('A'); >//Overloaded int main method public static void main(int a) < System.out.println(a); >//Overloaded char main method public static void main(char ch) < System.out.println(ch); >>

Frequently Asked Questions

The main method is used to specify the starting point of the program. This is the starting point of our program from where the JVM starts execution of the program.

No, you can’t declare a method inside main() method.

Yes we have can more than one main methods in java, however JVM will always calls String[] argument main() method. Other main() methods will act as a Overloaded method. In order to invoke these overloaded methods, we have to call them explicitly.

No, we cannot override main method of java because it is a static method and we cannot override a static method. The static method in java is associated with class which is why we don’t need an object to call these. Therefore, it is not possible to override the main method in java.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

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.

Источник

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