Error loading class java

Java — не удалось найти или загрузить основной класс

Популярное сообщение об ошибке для новых пользователей Java.

 Error: Could not find or load main class ClassName.class Caused by: java.lang.ClassNotFoundException: ClassName.class 

1. Нет пакета

1.1 Обзоры простой Java Hello World, без пакета.

 # Compile Java source code C:projects> javac HelloWorld.java C:projects> dir 15/04/2019 01:20 PM 425 HelloWorld.class 15/04/2019 01:42 PM 138 HelloWorld.java # Run Java C:projects>java HelloWorld.class Error: Could not find or load main class HelloWorld.class Caused by: java.lang.ClassNotFoundException: HelloWorld.class 

Чтобы исправить это, запустите java ClassName без .class расширение.

 C:projects>java HelloWorld Hello World 

2. С пакетом

2.1 Простой Hello World и package это так же как com.mkyong

 package com.mkyong; public class HelloWorld < public static void main(String[] args) < System.out.println("Hello World"); >> 
 # Compile Java source code C:projects> javac HelloWorld.java C:projects> dir 15/04/2019 01:20 PM 425 HelloWorld.class 15/04/2019 01:42 PM 138 HelloWorld.java C:projects>java HelloWorld Error: Could not find or load main class HelloWorld Caused by: java.lang.NoClassDefFoundError: com/mkyong/HelloWorld (wrong name: HelloWorld) 

2.2 Если package определяется, классы Java .class должен разместить в правильном месте папки.

Читайте также:  Non public classes java

Выше сгенерированный файл класса должен поместить в C:projectscommkyongHelloWorld.class

2.3 Чтобы исправить это , мы можем использовать -d указать, где разместить сгенерированные файлы классов.

 # Compile Java source code C:projects> javac -d . HelloWorld.java C:projects> dir 15/04/2019 02:01 PM com 15/04/2019 01:51 PM 161 HelloWorld.java C:projectscommkyongHelloWorld.class C:projectsHelloWorld.java 

2.4 Теперь мы можем бежать так java .HelloWorld

 C:projects>java HelloWorld Error: Could not find or load main class HelloWorld Caused by: java.lang.ClassNotFoundException: HelloWorld C:projects>java com.csharpcoderr.HelloWorld Hello World 

Рекомендации

Источник

Java Guide: How to Fix “Could not find or load main class”

Java Guide: How to Fix “Could not find or load main class”

The Java “Could not find or load main class” error is thrown when the JVM fails to find or load the main class while executing a program. It usually occurs when executing a Java program from the command line.

What Causes Error: Could not find or load main class

The «Could not find or load main class» error occurs when the JVM fails to load the main class. This can happen due to various reasons, such as:

  • The class being declared in the incorrect package.
  • The file path of the class not matching the fully qualified name.
  • Incorrectly specified classpath of the application.
  • Missing dependencies from the classpath.
  • Incorrect directory path on the classpath.
  • A typo in the class name.

Error: Could not find or load main class Example

Here’s an example of the Java «Could not find or load main class» error thrown when an incorrect class name is specified during execution:

Here’s an example Java class MyClass.java :

public class MyClass < public static void main(String[] args) < System.out.println("Hello World"); > >

Now the above class is compiled using the command line:

The compiler generates an executable .class file for MyClass:

$ ls MyClass.class MyClass.java

Now if the java command is used to execute the .class file with an incorrect name, the «Could not find or load main class» error is thrown:

$ java Myclass Error: Could not find or load main class Myclass

The generated .class file has the exact same name as the Java class, which in this case is MyClass.class . Specifying the correct name will execute the program successfully:

How to Fix Error: Could not find or load main class

There are several ways the «Could not find or load main class» error can occur while executing Java programs. Most of the time, it occurs because of specifying an incorrect class name, class file extension, file path or classpath.

The following tips can be useful to resolve the «Could not find or load main class» error:

  • Using correct class name — The spelling and casing of the class name should be checked when executing the program.
  • Using the class name without the .class extension — The java command expects the class name for executing the program, without the .class extension. Therefore, the following syntax should be used to execute Java classes: java
  • Using the correct file path — The path to the .class file should be checked and corrected if the error occurs. Remember to use the fully qualified name of the class that is in a package if executing it from outside the directory structure of the package.
  • Correct classpath definition — The classpath should be checked and defined correctly if the error comes up. It can also be specified using the java -cp or -classpath command line arguments.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Источник

Fix the Could Not Find or Load Main Class Error in Java

Fix the Could Not Find or Load Main Class Error in Java

  1. Could Not Find Error Due to Passing the Wrong Name in Java
  2. Could Not Find Error Due to Wrong Package Name in Java
  3. Could Not Find Error Due to Wrong CLASSPATH in Java

This tutorial introduces the could not find or load main class errors in Java.

Suppose we have written a code and compiled it. Till now, everything is working fine, but when we finally ran it, an error showed up.

could not find or load main class 

This tutorial will discuss why this error occurs and how to resolve it. Let us first recap how we run a java program using the command prompt.

First, we compile the code using the javac command like below:

After executing the above command, A file with the .class extension gets created into the current folder.

The .class file will have the same class as the .java program. We then run the .class file using the following command to execute the Java code:

We may get the could not find or load main class error. This error is a runtime error and occurs when the Java Virtual machine cannot locate the main class (class containing the main method) we are trying to run.

This error most commonly occurs when running our Java programs using the command prompt. Before discussing the causes of this error, let us first understand CLASSPATH.

CLASSPATH in Java

This is the executable.class and other resource files.

The JVM uses it to locate the files. The default CLASSPATH is the current directory unless we explicitly set the CLASSPATH in the system variables.

To run a program, we need to pass the class name. We take the following example to illustrate the point:

public class DelftStack  public static void main(String args[])  System.out.println("Hello from DelftStack");  > > 

Let’s first compile it using the javac command:

C:\Users\User\Documents\DelftStack\java>javac DelftStack.java C:\Users\USer\Documents\DelftStack\java> 

After the above command execution, a DelftStack.class file gets created in our current directory. Let’s run that file by using the java command.

C:\Users\User\Documents\DelftStack\java>java DelftStack.class Error: Could not find or load main class DelftStack.class Caused by: java.lang.ClassNotFoundException: DelftStack.class 

Here, we are getting an error because we are trying to run the .class file. Instead, we just need to pass the class name.

C:\Users\User\Documents\DelftStack\java>java DelftStack Hello from DelftStack 

Could Not Find Error Due to Passing the Wrong Name in Java

The could not find or load the main class can also occur when we pass the wrong class name. By continuing the previous example, if we try to run the program with the wrong name as follows:

C:\Users\User\Documents\DelftStack\java>java DelftStac Error: Could not find or load main class DelftStac Caused by: java.lang.ClassNotFoundException: DelftStac 

We get the error above because we have misspelled the class name. Here, the JVM is trying to run a class named DelftStac , which doesn’t exist.

We can resolve this issue by correctly spelling out the class name as follows:

C:\Users\User\Documents\DelftStack\java>java DelftStack Hello from DelftStack 

We should also note here that the class name is case-sensitive. If we run the class Delftstack , we will get an error.

C:\Users\User\Documents\DelftStack\java>java Delftstack Error: Could not find or load main class Delftstack Caused by: java.lang.NoClassDefFoundError: Delftstack (wrong name: Delftstack) 

We should use the correct spelling and the correct cases to run a file successfully.

Could Not Find Error Due to Wrong Package Name in Java

Let’s move our DelftStack class into the com.DelftStack package. A package is used to keep similar classes together.

Look at the following code:

package com.DelftStack;  public class DelftStack  public static void main(String args[])  System.out.println("Hello from DelftStack");  > > 

To compile a package in Java, we use the following command:

The -d flag switch is used to tell where to keep the generated class file. The . means the current directory.

We compile the above code as follows:

C:\Users\User\Documents\DelftStack\java>javac -d . DelftStack.java 

After executing the above command, the following folder structure gets created in our current directory.

com\DelftStack\DelftStack.class 

As we can see, our class file is two folders deep from our current directory. So if we try to run our class file like we were doing in previous cases, we get an error.

C:\Users\User\Documents\DelftStack\java>java DelftStack Error: Could not find or load main class DelftStack Caused by: java.lang.ClassNotFoundException: DelftStack 

The reason for this error is that no DelftStack class exists in our current folder. To run the class present in a package, we need to pass its fully qualified name ( com.DelftStack.DelftStack in this case).

C:\Users\User\Documents\DelftStack\java>java com.DelftStack.DelftStack Hello from DelftStack 

This tells Java to look for the class inside the com\DelftStack folder.

Could Not Find Error Due to Wrong CLASSPATH in Java

The CLASSPATH tells the JVM where the .class files are present.

Suppose we are currently in a different folder, and we want to run a Java program whose class file exists in a different folder. In this case, we can pass the location of the class file using the -classpath option.

java -classpath XYZ/ABC class name> 

The above command tells Java to look for the .class file inside the ZYX/ABC folder.

In the previous case, we created a package.

Suppose we want to run the file inside the com/DelftStack folder. Using the following command, we can do so:

>java -classpath ../../ com.DelftStack.DelftStack Hello from DelftStack 

The ../ means the parent directory. So ../../ means to lookup two directory levels.

Let us take another example, suppose we are at the desktop (folder) location, and we want to run a class file somewhere else on the computer. We can do so by below.

>java -cp C:\Users\User\Documents\DelftStack\java com.DelftStack.DelftStack Hello from DelftStack 

The -cp flag is the shorthand for -classpath . Here, we passed the full location of the folder where the .class file is present.

Related Article — Java Error

Copyright © 2023. All right reserved

Источник

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