Java virtual machine launcher could not find the main class как исправить

I'm trying to run SQuirreL SQL. I've downloaded it and installed it, but when I try to run it I get this error message: Java Virtual Machine Launcher. Could not find the main class. Program...

I’m trying to run SQuirreL SQL.
I’ve downloaded it and installed it, but when I try to run it I get this error message:

Java Virtual Machine Launcher.
Could not find the main class.
Program will exit.

I get the gist of this, but I have not idea how to fix it. Any help?

more info:

  • I’m on Windows XP pro.
  • I have java 1.6 installed, and other apps are running OK.
  • The install ran OK.
  • I believe I’ve followed the installation instructions correctly.
  • To run it, I’m invoking the squirrel-sql.bat file.

Update

This question: «Could not find the main class: XX. Program will exit.» gives some background on this error from the point of view of a java developer.

Community's user avatar

asked Sep 23, 2008 at 12:28

AJ.'s user avatar

5

Is Java installed on your computer? Is the path to its bin directory set properly (in other words if you type ‘java’ from the command line do you get back a list of instructions or do you get something like «java is not recognized as a …..»)?

You could try try running squirrel-sql.jar from the command line (from the squirrel sql directory), using:

java -jar squirrel-sql.jar

CharlesB's user avatar

CharlesB

84.4k27 gold badges189 silver badges214 bronze badges

answered Sep 23, 2008 at 12:39

MB.'s user avatar

MB.MB.

7,3076 gold badges42 silver badges42 bronze badges

3

The classpath is the path that the system will follow when trying to find the classes that you’re trying to run. In the batch file you’re trying to execute it probably has a variable like CLASSPATH=blah;blah;etc or a java command that looks similar to

java -classpath "c:directorylibsquirrel-sql.jar" com.some.squirrel.package.file

If you can find or add that classpath setting, make sure that it includes a path to the squirrel-sql.jar and any other jar files that it may depend on separated by semicolons (or the root /lib directory that may be included with the installation).

Basically you just need to tell java where to find the class files that you’re trying to execute. Wikipedia has a more indepth discussion about classpath and can offer you more insight. http://en.wikipedia.org/wiki/Classpath_(Java)

answered Sep 23, 2008 at 14:56

18Rabbit's user avatar

18Rabbit18Rabbit

3,1712 gold badges25 silver badges24 bronze badges

1

  1. JAVA_HOME variable must be set, to point to the prog files/java/version???/bin
  2. open squirrel-sql.bat file with some text editor and see if the JAVA_HOME variable there is the same as the one in your enviroment variable
  3. change it if it doesn’t match….and than run bat file again

answered Sep 26, 2008 at 12:06

tropikalista's user avatar

tropikalistatropikalista

1,6293 gold badges19 silver badges35 bronze badges

Have you followed these instructions:

http://www.squirrelsql.org/#installation

If so, are you running the batch file or the shell script to run it?

answered Sep 23, 2008 at 12:34

tim_yates's user avatar

tim_yatestim_yates

165k26 gold badges340 silver badges334 bronze badges

Tweaking MB’s answer for windows, will get rid of the console window:

start javaw -jar squirrel-sql.jar

answered Aug 21, 2009 at 16:31

Nathan Feger's user avatar

Nathan FegerNathan Feger

18.9k11 gold badges61 silver badges70 bronze badges

The .bat file does not seem to work.

Just double-click on:

squirrel-sql.jar

or type:

java -jar squirrel-sql.jar

in the command-line.

answered May 27, 2010 at 9:47

huug's user avatar

huughuug

1,0592 gold badges11 silver badges25 bronze badges

You can place .; in classpath in environmental variables to overcome this problem.

answered Jun 14, 2010 at 9:44

Sohail Anwar's user avatar

I tried to start SQUirrel 3.1 but I received a message stating «Could not find the main class FilesRationalClearQuestcqjni.jar» I noticed that C:Program FilesRationalClearQuestcqjni.jar is in my existing classpath as defined by the Windows environment variable, CLASSPATH.

SQUirrel doesn’t need my existing classpath, so I updated the SQUirrel bat file, squirrel-sql.bat.

REM SET SQUIRREL_CP=%TMP_CP%;%CLASSPATH%

SET SQUIRREL_CP=%TMP_CP%

It no longer appends my existing classpath to its classpath and runs fine.

answered Jun 28, 2010 at 17:21

Patrick's user avatar

I had this problem when I «upgraded» to Windows 7, which is 64-bit. My go to Java JRE is a 64-bit JVM. I had a 32-bit JRE on my machine for my browser, so I set up a system variable:

JRE32=C:Program FilesJavajre7

When I run:

"%JRE32binjava" -version

I get:

java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) Client VM (build 24.51-b03, mixed mode, sharing)

Which is a 32-bit JVM. It would say «Java HotSpot(TM) 64-Bit» otherwise.

I edited the «squirrel-sql.bat» file, REMarking out line 4 and adding line 5 as follows:

(4) rem set "IZPACK_JAVA=%JAVA_HOME%"
(5) set IZPACK_JAVA=%JRE32%

And now everything works, fine and dandy.

answered Apr 29, 2014 at 16:37

Steve Gelman's user avatar

I had the same issue with a different application (BI Publisher) because I installed a 32 bit version of this application on a 64 bit version of Windows.

Java Virtual Machine Launcher - could not find the main class

enter image description here

The solution for my case was to tell BI Publisher where to find the x86 version of JRE:

enter image description here

answered Oct 24, 2019 at 11:26

eby's user avatar

ebyeby

1111 silver badge4 bronze badges

I’m trying to run SQuirreL SQL.
I’ve downloaded it and installed it, but when I try to run it I get this error message:

Java Virtual Machine Launcher.
Could not find the main class.
Program will exit.

I get the gist of this, but I have not idea how to fix it. Any help?

more info:

  • I’m on Windows XP pro.
  • I have java 1.6 installed, and other apps are running OK.
  • The install ran OK.
  • I believe I’ve followed the installation instructions correctly.
  • To run it, I’m invoking the squirrel-sql.bat file.

Update

This question: «Could not find the main class: XX. Program will exit.» gives some background on this error from the point of view of a java developer.

Community's user avatar

asked Sep 23, 2008 at 12:28

AJ.'s user avatar

5

Is Java installed on your computer? Is the path to its bin directory set properly (in other words if you type ‘java’ from the command line do you get back a list of instructions or do you get something like «java is not recognized as a …..»)?

You could try try running squirrel-sql.jar from the command line (from the squirrel sql directory), using:

java -jar squirrel-sql.jar

CharlesB's user avatar

CharlesB

84.4k27 gold badges189 silver badges214 bronze badges

answered Sep 23, 2008 at 12:39

MB.'s user avatar

MB.MB.

7,3076 gold badges42 silver badges42 bronze badges

3

The classpath is the path that the system will follow when trying to find the classes that you’re trying to run. In the batch file you’re trying to execute it probably has a variable like CLASSPATH=blah;blah;etc or a java command that looks similar to

java -classpath "c:directorylibsquirrel-sql.jar" com.some.squirrel.package.file

If you can find or add that classpath setting, make sure that it includes a path to the squirrel-sql.jar and any other jar files that it may depend on separated by semicolons (or the root /lib directory that may be included with the installation).

Basically you just need to tell java where to find the class files that you’re trying to execute. Wikipedia has a more indepth discussion about classpath and can offer you more insight. http://en.wikipedia.org/wiki/Classpath_(Java)

answered Sep 23, 2008 at 14:56

18Rabbit's user avatar

18Rabbit18Rabbit

3,1712 gold badges25 silver badges24 bronze badges

1

  1. JAVA_HOME variable must be set, to point to the prog files/java/version???/bin
  2. open squirrel-sql.bat file with some text editor and see if the JAVA_HOME variable there is the same as the one in your enviroment variable
  3. change it if it doesn’t match….and than run bat file again

answered Sep 26, 2008 at 12:06

tropikalista's user avatar

tropikalistatropikalista

1,6293 gold badges19 silver badges35 bronze badges

Have you followed these instructions:

http://www.squirrelsql.org/#installation

If so, are you running the batch file or the shell script to run it?

answered Sep 23, 2008 at 12:34

tim_yates's user avatar

tim_yatestim_yates

165k26 gold badges340 silver badges334 bronze badges

Tweaking MB’s answer for windows, will get rid of the console window:

start javaw -jar squirrel-sql.jar

answered Aug 21, 2009 at 16:31

Nathan Feger's user avatar

Nathan FegerNathan Feger

18.9k11 gold badges61 silver badges70 bronze badges

The .bat file does not seem to work.

Just double-click on:

squirrel-sql.jar

or type:

java -jar squirrel-sql.jar

in the command-line.

answered May 27, 2010 at 9:47

huug's user avatar

huughuug

1,0592 gold badges11 silver badges25 bronze badges

You can place .; in classpath in environmental variables to overcome this problem.

answered Jun 14, 2010 at 9:44

Sohail Anwar's user avatar

I tried to start SQUirrel 3.1 but I received a message stating «Could not find the main class FilesRationalClearQuestcqjni.jar» I noticed that C:Program FilesRationalClearQuestcqjni.jar is in my existing classpath as defined by the Windows environment variable, CLASSPATH.

SQUirrel doesn’t need my existing classpath, so I updated the SQUirrel bat file, squirrel-sql.bat.

REM SET SQUIRREL_CP=%TMP_CP%;%CLASSPATH%

SET SQUIRREL_CP=%TMP_CP%

It no longer appends my existing classpath to its classpath and runs fine.

answered Jun 28, 2010 at 17:21

Patrick's user avatar

I had this problem when I «upgraded» to Windows 7, which is 64-bit. My go to Java JRE is a 64-bit JVM. I had a 32-bit JRE on my machine for my browser, so I set up a system variable:

JRE32=C:Program FilesJavajre7

When I run:

"%JRE32binjava" -version

I get:

java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) Client VM (build 24.51-b03, mixed mode, sharing)

Which is a 32-bit JVM. It would say «Java HotSpot(TM) 64-Bit» otherwise.

I edited the «squirrel-sql.bat» file, REMarking out line 4 and adding line 5 as follows:

(4) rem set "IZPACK_JAVA=%JAVA_HOME%"
(5) set IZPACK_JAVA=%JRE32%

And now everything works, fine and dandy.

answered Apr 29, 2014 at 16:37

Steve Gelman's user avatar

I had the same issue with a different application (BI Publisher) because I installed a 32 bit version of this application on a 64 bit version of Windows.

Java Virtual Machine Launcher - could not find the main class

enter image description here

The solution for my case was to tell BI Publisher where to find the x86 version of JRE:

enter image description here

answered Oct 24, 2019 at 11:26

eby's user avatar

ebyeby

1111 silver badge4 bronze badges

Over the years, computers have gotten relatively better at providing useful error messages. However, due to the complexity of modern software, sometimes you need a degree to even understand what you’re being told.

In this article, we’ll explain what the most common Java Virtual Machine errors mean and how you can resolve the underlying issues. Before we get to that, though, we first have to understand what a virtual machine is. Shall we begin?

What Is A Virtual Machine?

In layman’s term, a virtual machine allows your computer to simulate an entirely separate system. This makes it possible to run programs that otherwise wouldn’t be compatible with your system architecture – for instance, Android apps on a Windows PC. So what does this have to do with Java?

When a Java file is executed, it’s run through a version of the Java Virtual Machine before the code is interpreted. This means that if there’s a problem with the virtual machine, you won’t even be able to run Java programs until it’s been resolved.

“Java Virtual Machine Launcher Could Not Find The Main Class”

This sounds like a pretty serious error but in actuality, it’s one of the easiest to fix. Generally, if you’re seeing this, something has gone wrong with your Java installation. All you have to do is reinstall it. To do this:

  • Uninstall your previous Java installation. For Windows users, this is done in the Control Panel’s Programs and Features submenu.

java virtual machine error

  • Next, go to Java’s site and select the correct version for your operating system.
  • Restart your computer and try running the Java file again.

“Could Not Create The Java Virtual Machine”

Here’s another example of a vague error message that doesn’t actually help you in any way. The good news is that this error usually has one specific cause: Java is trying to use more memory than your system actually has. So how do you fix this?

  • Begin by opening the Control Panel.
  • Click System, then Advanced Systems Properties, then Environment Variables

java vm error

  • Click the Add button
  • Set the New Variable Name to “_JAVA_OPTIONS” without the quotation marks.
  • Set the value to -Xmx512M” without the quotation marks. The digits before the M refer to the maximum amount of RAM allocated to Java. For instance, you could also use “-Xmx1024M” or “-Xmx256M”, if you had more or less memory to spare.

Fixes To Avoid

There are a few solutions that users on internet forums LOVE to suggest, but while they mean well, you are highly unlikely to see your problem resolved by:

  • Running an anti-malware scan (a virus that only messes with your Java Runtime Environment? For what purpose?).
  • Clearing your cache. This has nothing to do with Java, whatsoever.

how to fix java virtual machine error

  • Changing registry values. While this has the potential to resolve very specific problems, it can have catastrophic effects on your operating system and you’re more likely to break something than fix it.
  • Reinstalling your operating system. This is like amputating an arm because of a broken fingernail! Problems with a single software package can be easily resolved and won’t lead to you losing all your files, as with a fresh installation.

Do you need to update Javascript? We have an easy and helpful guide on how to update it. Read it here!

Conclusion

Java Virtual Machine errors are rarely as serious as they appear. In fact, we’ve shown that the most common errors can be resolved in a few steps. Even though the exact options you’ll need will differ from one operating system to another, at least you now know what you have to do.

Now that you’ve read on how to fix Java Virtual Machine Launcher Error, take time to read on how to log into Kronos Timekeeper from home.

how does a gfci outlet work

How Does A GFCI Outlet Work?

The main() method is required to run/execute programs developed in the Java programming language since it is where the program execution begins. When starting a Java program, you could encounter the warning “error: Could not find or load main class.” You’re having this problem because you’re using the java command to run main() from within the class.

Note: You can also learn Errors and Exception in Python.

How to fix could not find or load the main class?

There are many ways to solve this issue depending on the reason of occurring this error. We will discuss each reason one by one and try to fix this problem.

What are the possible causes or reasons of this error?

There are several reasons for this problem, which are listed below.

  • File Extension
  • Wrong Package
  • Classpath is not valid
  • The class name is incorrect

File Extension

We need to save the Java source code file with the extension .java to compile it. To compile a Java program, Java Compiler is being used as (javac command). After compilation, the .java file will be converted to a .class file.

As a result, your source code file will end in.java, while the produced file will end in .class. For compiling source code, we were using filename, but for running a compiled file, we cannot use the file name but the class name. Else it will throw an error like in the below example.

Example: HelloWorld.java

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

Compiling HelloWorld Program

Compilation

Running/Executing HelloWorld with the filename.

Running/Executing HelloWorld with the class name.

Wrong Package

Packages used in Java for group-related classes to write better maintainable code. To avoid name conflicts in group classes, we can use packages in Java programming. To launch a Java class in a package, we must use packageName with a fully qualified className. We cannot run it directly using the class name as in the previous example, and if we do so, we will get the error.

Example: HelloWorld.java

Package com.baeldung;
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
 

Compiling HelloWorld Program

Running/Executing HelloWorld without package name.

without package name

Running/Executing HelloWorld with the class name.

with package name

It is still showing an error because it could not find the HelloWorld file inside com/baeldung. We need to move back to the parent directory and rerun it.

Classpath is not valid.

The Java Virtual Machine searches the classpath for user-defined classes, packages, and resources in Java programs. If you correctly stated the class name but still received the same error, the Java command likely could not locate the supplied class name at the location. As a result, you must first confirm that the location of your .class file is included in your classpath.

Example: HelloWorld.java

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

Compiling HelloWorld Program

Running/Executing HelloWorld at the default location.

default location

Running/Executing HelloWorld at the location where the file exists.

file location

The class name is incorrect.

This problem can occur if the name of your Java file (.java) and the primary class name is different. For the example, we have done class name HelloWorld, and the file name is HelloWorld.java. Let change the class name and execute the program.

Example: HelloWorld.java

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

Compiling HelloWorld Program

Conclusion

In this article, we tried to resolve a Java error that could not find or load the main class differently. We discussed some reasons for this error and, depending on those reasons, applied the methods to fix the error. Also, we performed coding examples with executions with error-occurring conditions and solved the error accordingly.

The virtual machine or processor inside your computer that provides an environment for all the Java programs to run on your computer is the Java Virtual Machine. It is a set of specifications of an abstract machine that loads the file containing the programming, interprets it and also helps it being executed it.

Thus the JVM takes the byte code of the program, which is stored in a ‘.class.’ Format and converts it into the operating system specific code, which the machine can read and hence can be run on your computer. So without the proper functioning of this virtual machine on our computers, the many Java-based applications will not be running on our computers!

But that is precisely what happens very often (while booting the computer or opening a java based application) and we get an error called the Java Virtual Machine Launcher Error. In this article, we will be talking about the standard Java Virtual Machine Launcher errors, the kind of error messages that will come up when you are having a particular problem and how to go about solving these problems.

See also: What Is Server Virtualization | How It Works And Its Benefits!

Contents

  • 1 4 Solutions to Solve Java Virtual Machine Launcher Error
    • 1.1 Remove Malware on your computer
    • 1.2 Uninstalling Java and re-installing
    • 1.3 Clearing Computer Memory
    • 1.4 Miscellaneous Fix
  • 2 Conclusion

4 Solutions to Solve Java Virtual Machine Launcher Error

Remove Malware on your computer

If the error message is shown is this- “Error Message: Java Virtual Machine Launcher could not find the main class: the program will now exit” then the Microsoft Malicious Software Removal tool, which is an inbuilt utility tool in Microsoft can be used to remove any Malware from your computer.

To access this tool, go to the Search Windows option in your Start menu and type “mrt” and press Enter. In The tool, choose the option for “Full Scan” and follow the on-screen wizard to start the scan. The scan may take a few moments to complete and in the process will also remove all the Spyware, Adware and Malware on your computer. Reboot your computer once the scan is complete.

Now using the System Configuration tool on your computer the rest of the problem. To launch this, you need to type “msconfig” in the Search Windows option that you can find in the Start Menu. In this utility tool, click the “Startup” tab, which opens a long list. Scan the list to find the following- “WJView.exe” and “javaw.exe.” and uncheck these options.

See also: – [Solved] Failed To Enumerate Objects in the Container

Uninstalling Java and re-installing

As the heading suggests, this solution involves uninstalling the problematic Java Virtual Machine launcher from your computer and then installing it afresh. This is a quite primitive but effective solution to Java Virtual Machine launching problems when the error message shows- “Error Message: Error opening registry key.”

Before uninstallation, open the Windowssystem32 and delete the following files- ‘javaws.exe’, ‘java.exe’, ‘javaw.exe’ and any other Java executable file that you can find. For uninstalling JVM, open the ‘Programs and Features’ tab in the Control Panel of your desktop. Scroll down the list to find Java runtime and uninstall it.

For re-installing Java runtime, visit java.com: Java + You and download the most compatible version. Choosing the correct version is very important as an incompatible version of Java Runtime is one of the biggest reasons for the error.

Clearing Computer Memory

One of the most frequent reasons for the Java Virtual Machine launcher problems is insufficient memory in your COMPUTER. This insufficiency may be in your overall computer memory or in the amount of memory you allocate to Java Runtime. To solve the former, just get rid of all those programs that you don’t use, and you will have a clutter-free (and hopefully a problem-less) computer.

When Java has allocates insufficient memory space, then the error that comes is- “Error Message: Could not create the Java Virtual Machine.” This is one of the most common Java Virtual Machine Launcher errors that you encounter during playing games on Java like Minecraft.

To solve the memory space allocated to Java, go to the Systems options in Control Panel and open the Advanced options window. Here, clicking on the Environment Variables option, you will find a ‘System Variables’ option. Click on the ‘New’ variable option and put the name of the variable as ‘_JAVA_OPTIONS’ with a value of ‘Xmx512M’. (Xmx refers to the maximum space and Xms refer to the minimum space that you can allocate to Java)

See also: – Top 4 Best Virtual Machine Applications for Windows 10 – TechWhoop

Miscellaneous Fix

This solution is for the Java Virtual Machine Launcher error prompt- “Error Message: Unable to access jarfile.” Which comes when trying to open some java based applications. Start by opening the ‘Default Programs’ tab from the Start Menu. Scan the list to find an option called- ‘Associate a file type or protocol with a program’ and select it.

There will be an extension ‘.jar’- Click on this and change the default program to ‘JAVA virtual machine launcher’. Clicking on ‘Close’ will save the changes. Try reopening the program that was earlier causing the problem.

Conclusion

Hopefully, by following this article, you will solve the Java Virtual Machine Launcher error, and all your Java-based applications and games will be up and running smoothly again. There is also this hack if you want to assess your Java skills! All suggestions regarding alternative methods to resolve the launcher error are welcome.

Introduction

Java developers often face the ‘could not find or load main class’ error out of the blue during compilation. If you keep getting this error without any specific reason, you are not alone. Whether you’re just starting out as a programmer or have some experience under the belt, we’ve all seen this error at least once. And we know it has nothing to do with our code.

Why does the “JVM could not find or load the main class” error occur?

As the name suggests, the ‘could not find or load main class’ error means that the JVM (Java Virtual Machine) could not locate the main class in your code and throws this runtime error. The question is can we not find it?

It is one of the most unpredicted and spontaneous errors in Java, which occurs due to the tendency of JVM to stick with a default classpath, the “main class not found issue” is something that haunts amateurs and professionals alike. As serious as it seems, it is not that difficult to fix. We will be exploring in this article how you can easily fix this annoying Java compilation error.

new java job roles

What Is Classpath?

Before we dive into the how and why of it, we need to understand what Classpath is and its role in Java.

The classpath is the file path where the JRE (Java runtime environment) searches for the classes and other resource files to run the code. As the name suggests, it is simply a file path where the .class format files can be found in a JDK package or directory.

Classpath can be set using two ways:

  1. Using the -classpath option at the time of executing the code,
  2. By setting the file path to the system CLASSPATH environment variable.

When the JVM is unable to locate the main class, it is usually because you would have entered the wrong .class name to run the classpath or the corresponding .class files have been altered.

See this example of generating a class file of a simple code:

1. public class example01 {
2. public static void main(String[] args) {
3. out.println("This is a simple code");
4. }
5. }

To run a .class file, you can use the following command:

java <.class filename>

Now if we run this line of code to run the class we made.

$ java eg01

Output:

Error: Could not find or load main class

It will fail with the error “Could not find or load main class eg01.”

As mentioned earlier, the .class file will have the same name given to the Java class of the program. So, in this case, the main class will have the name example01, not eg01.

Let’s try this one more with the correct name:

$ java example01

Output:

This is a simple code

Now it ran successfully.

While it’s not as simple in a project, the easiest way to rectify it is by either manually specifying the classpath or using packages.

Using Packages

Packages are used in Java to group similar classes or to provide a unique namespace to a group of classes. We will be now creating a class called example02 and place it in a package called example02Package.

1. package example02Package;
2. public class example02 {
3. public static void main(String args[]) {
4. out.println("File is found successfully!");
5. }
6. }

We will then use this package to visualize how the classpath works in Java. In your files directory, a package is represented as an independent folder by its name that you can easily observe in a file manager application.

After ensuring that the working directory is the same as the one that contains the package folder, you can also change the working directory on the terminal (command prompt) by using the cd command on almost every popular operating system.

Example02.java can be compiled by running the following command:

  1. package example02Package;
  2. javac example02Package/example02.java

This will now save the compiled .class file in the example02Package directory.

To run the compiled class, you need to type in the fully qualified class name in the command line. The fully qualified name of a Java class is written by prefixing it with the package name.

For this example, this is the fully qualified name:

java example02Package.example02

Using packages also allows Java developers to call executables from different packages from the same working directory. It can be easily done just by modifying the fully qualified class name without getting the ‘could not find or load main class error.

Manually Specifying Classpath

The other way to prevent could not find or load main class error is by manually specifying the classpath. It is recommended to manage your java files by creating separate directories for all source files and classes.

Just like the .class files are labeled as classes. the directory with source files is labeled as src. It also helps in significantly reducing the chances of JVM not being able to find the main class.

If you use this method for organization, this is how the directory structure of your projects will look like before compilation:

|___Project01
|     |___src
|           |___example02Package
|                       |___example02.java
|
|     |___classes

The indentations in the above example show the one level of the file hierarchy that your project should be following.

When compiling this code, you must make sure that your working directory is Project01. The following command is used to execute it:

javac -d classes src/testPackage/Test.java

The .class executable file must be saved in Project01/classes/example02Package. Now, the file directory structure will look like this:

|___Project01
|     |___src
|           |___example02Package
|                       |___example02.java
|
|         classes
|           |___example02Package
|                       |___example02.class

To run the .class file, you have to run the Java command with the fully qualified class name and the specification of the local classpath. Every path is declared relative to the working directory, which in this example is Project01.

java -classpath classes example02Package

Running this command will now provide you with the desired output without any chances of getting the error. The question is, why do you need to reorganize the files to solve such a small runtime error?

Why Organizing Files is important in Java?

The primary reason behind why the ‘could not find or load main class ’ is encountered is because JVM is unable to locate where your .class files were being saved.

The easiest way to resolve this error and prevent it from ever happening is to organize where the .class files are saved. Developers have to explicitly indicate the JVM to look for the .class file in the assigned location. This can only be done by organizing the source files and executables separately and using the working directory to manage either manually or using packages.

Your project code will likely keep expanding over time as the project work keeps going. By adding more constructs such as inheritance, inner classes, and more to your project, the file system keeps getting more complex. In such projects, this simple practice of organizing files can save you several hours of precious time that it would take in debugging if something goes wrong and you end up getting the could not find or load main class error.

See Also: What Are Annotations in Java – How do They Work

Conclusion

“Could not find or load main class” error is very common in Java however, we have discussed some effective ways to prevent this error in the article above. The file organization methods we discussed not only prevent this error but also make your code and directories manageable. These fixes go a long way for Java developers as they save a lot of time and trouble when debugging, especially for complex codes!

new Java jobs

  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

Fix the Could Not Find or Load Main Class Error 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:UsersUserDocumentsDelftStackjava>javac DelftStack.java
C:UsersUSerDocumentsDelftStackjava>

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

Look below:

C:UsersUserDocumentsDelftStackjava>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:UsersUserDocumentsDelftStackjava>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:UsersUserDocumentsDelftStackjava>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.

Look below:

C:UsersUserDocumentsDelftStackjava>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:

javac -d . <.java file name>

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:UsersUserDocumentsDelftStackjava>javac -d . DelftStack.java

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

comDelftStackDelftStack.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:UsersUserDocumentsDelftStackjava>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:UsersUserDocumentsDelftStackjava>java com.DelftStack.DelftStack
Hello from DelftStack

This tells Java to look for the class inside the comDelftStack 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.

For example:

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

Понравилась статья? Поделить с друзьями:
  • Java version error could not open
  • Java util zip zipexception error in opening zip file
  • Java util nosuchelementexception ошибка
  • Java util concurrent timeoutexception как исправить
  • Java update error 1618