Error main method not found in class main please define the main method as

New Java programmers often encounter messages like the following when they attempt to run a Java program. (Different Java tools, IDEs and so on give a variety of diagnostics for this problem.) Er...

When you use the java command to run a Java application from the command line, e.g.,

java some.AppName arg1 arg2 ...

the command loads the class that you nominated and then looks for the entry point method called main. More specifically, it is looking for a method that is declared as follows:

package some;
public class AppName {
    ...
    public static void main(final String[] args) {
        // body of main method follows
        ...
    }
}

The specific requirements for the entry point method are:

  1. The method must be in the nominated class.
  2. The name of the method must be «main» with exactly that capitalization1.
  3. The method must be public.
  4. The method must be static 2.
  5. The method’s return type must be void.
  6. The method must have exactly one argument and argument’s type must be String[] 3.

(The argument may be declared using varargs syntax; e.g. String... args. See this question for more information. The String[] argument is used to pass the arguments from the command line, and is required even if your application takes no command-line arguments.)

If anyone of the above requirements is not satisfied, the java command will fail with some variant of the message:

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

Or, if you are running an extremely old version of Java:

java.lang.NoSuchMethodError: main
Exception in thread "main"

If you encounter this error, check that you have a main method and that it satisfies all of the six requirements listed above.


1 — One really obscure variation of this is when one or more of the characters in «main» is NOT a LATIN-1 character … but a Unicode character that looks like the corresponding LATIN-1 character when displayed.
2 — Here is an explanation of why the method is required to be static.
3 — String must be the standard java.lang.String class and not to a custom class named String that is hiding the standard class.

The java error: main method not found in the file, please define the main method as: public static void main(string[] args) occurs if the main method not found in class or the main method is not accessible or the main method is invalid. The main method indicates the start of the application. The main method syntax must be as public static void main(String[] args) { }. Alternatively, java program must extend javafx.application.Application. Otherwise, “or a JavaFX application class must extend javafx.application.Application” error will be shown.

In Java, each application must have the main method. The main method is the entry point of every java program. The java program searches for the main method while running. This error occurred when the main method is not available.

In java, the JavaFX application does not to have a main method, instead the JavaFX application must extend javafx.application.Application class. Otherwise “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” exception will be thrown in java.

Exception

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
Error: Main method is not static in class, please define the main method as:
   public static void main(String[] args)
Error: Main method must return a value of type void in class, please 
define the main method as:
   public static void main(String[] args)

Error Code

The Error code looks like as below. If you run javac Test.java & java Test The above exception will be thrown. The Test class neither have main method nor extend javafx.application.Application class.

package com.yawintutor;

public class Test {

}

Root Cause

Spring boot is looking for the main method to start the spring boot application. This error occurred because the main method is not available.

Any one of the following is the possible cause of this issue

  • The main method is deleted
  • The main method name is renamed
  • The signature of the main method is changed
public static void main(String[] args) {
// block of code 		
}

Solution 1

The java main method is the entry point of the java program. If the main method is missing in the program, the exception will be thrown. Check the main method in the code, and add the main method as shown below.

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

The below example shows the main method of the spring boot application.

package com.yawintutor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringHelloWorldApplication {

	public  void main(String[] args) {
		SpringApplication.run(SpringHelloWorldApplication.class, args);
	}

}

Solution 2

The main method in the java application must be public. If it is not a public, java compiler can not access the main method. If the access specifier is not specified or not a public, then the exception will be thrown.

package com.yawintutor;

public class Test {
	static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Output

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

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Solution 3

If the main method does not have static keyword, the main method can not access from outside of the class. The object of the class only can access the main method. To create a object, the main method must be executed. This will cause the exception.

package com.yawintutor;

public class Test {
	public void main(String[] args) {
		System.out.println("Hello World");
	}
}

Output

Error: Main method is not static in class com.yawintutor.Test, please define the main method as:
   public static void main(String[] args)

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Solution 4

The main method must return void. If the return data type is added other than void. the exception will be thrown.

package com.yawintutor;

public class Test {
	public static int main(String[] args) {
		System.out.println("Hello World");
		return 0;
	}
}

Output

Error: Main method must return a value of type void in class com.yawintutor.Test, please 
define the main method as:
   public static void main(String[] args)

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Solution 5

The main method must have only one argument. The argument must be a string array. If no argument is configured or different data type argument is configured or more than one argument is configured, the exception will be thrown.

package com.yawintutor;

public class Test {
	public static void main() {
		System.out.println("Hello World");
	}
}

Output

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

Solution

package com.yawintutor;

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

How to create simple Spring Boot Application with Main method

Have you ever tried to reason why Java’s main() method is public, static and void? Why its name is main? What happens inside JVM when you invoke main() method? What is the purpose of main method? Let’s find out.

  1. 1. Java main() Method Syntax
  2. 2. Why Java main Method is public?
  3. 3. Why static?
  4. 4. Why void?
  5. 5. Why the name is main?
  6. 6. What happens internally when you invoke main method?
  7. 7. main() method native code in java.c
  8. 8. Summary

1. Java main() Method Syntax

Start with reminding the syntax of the main method in Java.

public class Main
{
    public static void main(String[] args)
    {
        System.out.println("Hello World !!");
    }
}

2. Why Java main Method is public?

This is a big question and perhaps most difficult to answer, too. I tried hard to find a good reason for this question in all the good learning material in my reach, but nothing proved enough.

So, my analysis says (like many others): the main method is public so that it can be accessible everywhere and to every object which may desire to use it for launching the application.

Here, I am not saying that JDK/JRE had this exact similar reason because java.exe or javaw.exe (for windows) can use Java Native Interface (JNI) to execute the invoke method for calling the main() method, so they can have invoked it, either way, irrespective of any access modifier.

A second way to answer this is another question, why not public? All methods and constructors in java have some access modifier. The main() method also needs one. There is no reason why it should not be public, and be any other modifier(default/protected/private).

Notice that if we do not make main() method public, there is no compilation error. You will runtime error because the matching main() method is not present. Remember that the whole syntax should match to execute main() method.

public class Main
{
    void static main(String[] args)
    {
        System.out.println("Hello World !!");
    }
}

Program Output:

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

3. Why static?

Another big question. To understand this, let suppose we do not have the main method as static. Now, to invoke any method you need an instance of it. Right?

Java can have overloaded constructors, we all know. Now, which one should be used, and from where the parameters for overloaded constructors will come. These are just more difficult questions, which helped Java designers to make up their minds and to have the main method as static.

Notice that if you do not make main() method static, there is no compilation error. You will runtime error.

public class Main
{
    public void main(String[] args)
    {
        System.out.println("Hello World !!");
    }
}

Program Output:

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

4. Why void?

Why should it not be void? Have you called this method from your code? NO. Then there is no use of returning any value to JVM, who actually invokes this method. It simply doesn’t need any returning value.

The only thing application would like to communicate to the invoking process is normal or abnormal termination. This is already possible using System.exit(int). A non-zero value means abnormal termination otherwise everything was fine.

5. Why the name is main?

No rock-solid reason. Let us assume because it was already in use with C and C++ language. So, most developers were already comfortable with this name.

Otherwise, there is no other good reason.

6. What happens internally when you invoke main method?

The purpose of the main method in Java is to be a program execution start point.

When you run java.exe, then there are a couple of Java Native Interface (JNI) calls. These calls load the DLL that is really the JVM (that’s right – java.exe is NOT the JVM). JNI is the tool that we use when we have to bridge between the virtual machine world, and the world of C, C++, etc. The reverse is also true. It is not possible to actually get a JVM running without using JNI.

Basically, java.exe is a super simple C application that parses the command line, creates a new String array in the JVM to hold those arguments, parses out the class name that you specified as containing main(), uses JNI calls to find the main() method itself, then invokes the main() method, passing in the newly created string array as a parameter.

This is very, very much like what you do when you use the reflection from Java, it just uses confusingly named native function calls instead.

It would be perfectly legal for you to write your own version of java.exe (the source is distributed with the JDK), and have it do something entirely different.

7. main() method native code in java.c

Download and extract the source jar and check out ../launcher/java.c. It is something like this:

/*
* Get the application's main class.
*/
if (jarfile != 0) {
mainClassName = GetMainClassName(env, jarfile);
... ...

mainClass = LoadClass(env, classname);
if(mainClass == NULL) { /* exception occured */
... ...

/* Get the application's main method */
mainID = (*env)->GetStaticMethodID(env, mainClass, "main", "([Ljava/lang/String;)V");
... ...

{/* Make sure the main method is public */
jint mods;
jmethodID mid;
jobject obj = (*env)->ToReflectedMethod(env, mainClass, mainID, JNI_TRUE);
... ...

/* Build argument array */
mainArgs = NewPlatformStringArray(env, argv, argc);
if (mainArgs == NULL) {
ReportExceptionDescription(env);
goto leave;
}

/* Invoke main method. */
(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);

So, here you can see what happens when you invoke a java program with the main method.

8. Summary

Java’s main method is used by all developers and everybody knows the basic syntax to write it. Yet, very few completely understand the correct reasoning and the way it works.

In this post, we got a very basic understanding of the things behind the main method that is the primary starting point of an application.

Happy Learning!!

23 ноября, 2022 11:57 дп
54 views
| Комментариев нет

Development, Java

main в Java – это обычно первый метод, о котором узнают начинающие, потому что он является точкой входа в программирование на Java. Метод main может содержать код для выполнения или вызова других методов и его можно вложить в любой класс, который является частью программы. Более сложные программы обычно содержат класс, в котором есть только метод main. Название класса, содержащего main, может быть любым, но обычно его называют просто класс Main.

В следующих примерах класс, содержащий метод main, называется Test:

public class Test {

public static void main(String[] args){

System.out.println("Hello, World!");
}
}

В этом мануале мы разберем, что значит каждая составляющая данного метода.

Синтаксис метода Main

Синтаксис метода всегда выглядит так:

public static void main(String[] args){
// some code
}

Изменить здесь можно только название аргумента массива String. Например, вы можете изменить args на myStringArgs. Аргумент массива String может быть записан как String… args или String args[].

Модификатор public

Чтобы JRE могла получить доступ к main методу и выполнить его, модификатором доступа этого метода должен быть public. Если метод не является public, доступ к нему будет ограничен. В следующем примере кода в методе main модификатор доступа public отсутствует:

public class Test {

static void main(String[] args){

System.out.println("Hello, World!");
}
}

Возникает ошибка при компиляции и запуске программы. Это происходит потому, что метод main не является общедоступным и JRE не может его найти:

javac Test.java 

java Test

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

Модификатор static

При запуске Java-программы объект класса отсутствует. Чтобы JVM могла загрузить класс в память и вызвать main метод без предварительного создания экземпляра класса, main методу нужен модификатор static. В следующем примере кода в main методе нет модификатора static:

public class Test {

public void main(String[] args){

System.out.println("Hello, World!");
}
}

Так как метод main не имеет модификатора static, при компиляции и запуске программы возникает следующая ошибка:

javac Test.java 

java Test

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

Модификатор void

Каждый метод Java должен указывать тип возвращаемого значения. Тип возвращаемого значения main метода в Java — void, поскольку он ничего не возвращает. Когда main метод завершает выполнение, программа Java завершает работу, поэтому в возвращаемом объекте нет необходимости. В следующем примере метод main пытается что-то вернуть при типе возврата void:

public class Test {

public static void main(String[] args){
return 0;
}
}

При компиляции программы возникает ошибка, потому что Java не ожидает возврата значения, когда тип возврата void:

javac Test.java

Test.java:5: error: incompatible types: unexpected return value
return 0;
       ^
1 error

Метод main

При запуске программа Java всегда ищет метод main. Данный метод может называться только так, его нельзя переименовывать. В следующем примере кода мы для наглядности переименовали main метод в myMain:

public class Test {

public static void myMain(String[] args){

System.out.println("Hello, World!");
}
}

Во время компиляции и запуска программы возникает ошибка, так как JRE не находит метод main в классе:

javac Test.java 

java Test

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

Массив String[] args

Main принимает один аргумент массива String. Каждая строка в массиве является аргументом командной строки. Их можно использовать, чтобы влиять на работу программы или передавать в нее информацию во время выполнения. Далее показано, как вывести аргументы командной строки при запуске программы:

public class Test {

public static void main(String[] args){

     for(String s : args){
System.out.println(s);
     }
    }
}

Когда скомпилируете программу и потом запустите ее с несколькими аргументами командной строки, разделенными пробелами, аргументы будут выводиться в терминале:

javac Test.java 

java Test 1 2 3 “Testing the main method”

1
2
3
Testing the main method

Заключение

В этой статье мы подробно остановились на каждом компоненте метода main в Java. 

Читайте также: Как написать свою первую программу на Java

Tags: Java

Понравилась статья? Поделить с друзьями:
  • Error main file version
  • Error main file cannot be included recursively when building a preamble
  • Error main cannot start client command adb
  • Error mail command failed 550 not local sender over smtp
  • Error macro mortal kombat