Monday, July 26, 2021

Error: Could not find or load main class in Java [Solved]

Error: Could not find or load main class HelloWorld comes when you are trying to run your Java program using java command with the main class as HelloWorld but Java is not able to find the class. In order to solve this error, you must know how Java find and loads the classes, that's a little bit complex topic for beginners, but we will touch the same base here. For the curious reader, I would suggest reading my post How Classpath works in Java, a must read for a beginner. For now, you just remember that there is an environment variable called CLASSPATH which includes directories where Java looks for all class files and if it doesn't find your main class there then it throws "Error: Could not find or load main class XXX", where XXX is the name of your main class.

Since many Java programmer is now started programming using Eclipse they face this issue when they first try to run their Java program from command line. In Eclipse, it's easy to compile and run the program because Eclipse takes care of all Classpath setup, but when you run your Java program from command line, CLASSPATH environment variable comes in picture.

Personally, I don't like this environment variable and doesn't define in my environment variable, because its confusing and source of so many classpath related issue. Instead, I use -cp or -classpath option with java command to run my program. This way you always know which JARs are included in your classpath.




For beginners, another important thing to understand is the difference between PATH and CLASSPATH, you must know that PATH is used locate system executable, commands or .exe, .dll files (in Windows) and .so files (in Linux). It is also used to locate native libraries used by your Java program. While, CLASSPATH is used to locate the class file or JAR files. It's Java class loader who looked into CLASSPATH for loading classes.


Coming back to the problem in hand, if you are a beginner in Java, who are able to run the program from Eclipse but getting "Error: Could not find or load main class HelloWorld" when trying to run the same program from the command line then follow the steps given here to solve it.



Solving Error: Could not find or load main class HelloWorld 

Unfortunately beginner's book like Head First Java, which many developers used to learn Java, doesn't teach you how to deal with this kind of errors. You need to build this skill by doing active development.  In order to understand the problem little better, let's reproduce it. This is one of the most important troubleshooting skill which will help you a long way in your career. Half of the problem is solved when you are able to reproduce it.

For our purpose we will use following HelloWorld program for our testing, interestingly I have named it HelloHP and it resides in a package called "dto". I have purposefully chosen a class with a package instead of HelloWorld in the default package because many programmers get "Could not find or load main class" error when they try to run a class which is inside a package.

package dto;
/**
 * Simple Java program to demonstrate following error
 * Error :Could not find or load main class
 * 
 * @author Javin Paul
 */
public class HelloHP {

    public static void main(String args[]) {
        System.out.println("My first program in Java, HelloWorld !!");
       
    }

}

When you run this from Eclipse, by Right click on the source file and Choosing "Run as Java Program", it will run fine and print following line:

My first program in Java, HelloWorld !!

Everything as expected, Now we will try to run same Java program from command line. Since I am using Maven with Eclipse, its build process creates class files in project_directory\target\classes directory. If you are not using Maven with Eclipse, then you can see the class file created by Eclipse's Java compiler in project_directory\bin. It doesn't matter how those class files are created, but, what is important is the location of the class file.

If your class is inside a non-default package e.g. "dto" in our case then compiler the will put the HelloHP.class file, which contains Java bytecode in a directory named "dto". In our case the full name of class dto.HelloHP and it is present in C:\Users\WINDOWS 8\workspace\Demo\target\classes\dto. So in the first try, I go there and execute java command to launch my program, as seen below:

C:\Users\WINDOWS 8\workspace\Demo\target\classes\dto>java HelloHP
Error: Could not find or load main class HelloHP

Do you see the error? It's coming because the full name of the class should be dto.HelloHP and not HelloHP. So let's correct this error and try to run the same command from the same location but this time with fully qualified name:

C:\Users\WINDOWS 8\workspace\Demo\target\classes\dto>java dto.HelloHP
Error: Could not find or load main class dto.HelloHP

Still same error, right. Why? because I don't have any CLASSPATH environment variable, neither I am using -classpath or -cp option to suggest the path, So by default Java is only searching in the current directory. It is looking for dto/HelloHP.class but since we are already inside dto, it is  not able to find the class. So, what should we do now? let's go to the parent directory "C:\Users\WINDOWS 8\workspace\Demo\target\classes" and execute the same command, this time, it should work:

C:\Users\WINDOWS 8\workspace\Demo\target\classes\dto>cd ..

C:\Users\WINDOWS 8\workspace\Demo\target\classes>java dto.HelloHP
My first program in Java, HelloWorld !!

Bingo!!, our program ran successfully because, without any hint about where to find class files, Java is by default looking into the current directory, denoted by . (dot) and able to locate ./dto/HelloHP.class.

Now, what if you want to run this program from any other directory? Well, for that purpose whether we need to define CLASSPATH or just use -classpath or -cp option. I like the second option because it's easier to control and change. Also, remember, it overrides any CLASSPATH environment variable. If you like to set CLASSPATH environment variable in Windows, see that tutorial.

Now let's run the program target directory first without using -classpath option:

C:\Users\WINDOWS 8\workspace\Demo\target\classes>cd ..

C:\Users\WINDOWS 8\workspace\Demo\target>java dto.HelloHP
Error: Could not find or load main class dto.HelloHP

You can see we are again started getting the same error, Why? because Java is still looking into the current directory and there is no .\target\dto\HelloHP.class there, as it's one level down e.g. .\target\classes\dto\HelloHP.class

Now let's run the same command using -classpath option from target directory itself:

C:\Users\WINDOWS 8\workspace\Demo\target>java -cp ./classes;. dto.HelloHP
My first program in Java, HelloWorld !!

Bingo!!, our program ran successfully again because now Java is also looking at ./classes directory and there it is able to find dto\HelloHP.class file.

There are many ways Error: Could not find or load main class HelloWorld manifests itself, but if you know the basics of Java Classpath, you can easily sort out the problem. Most of the time you just need to either correct your CLASSPATH environment variable or run your program with java -cp or -classpath option. By the way, there are more to it e.g. Main class defined in the manifest.mf file and that's why I suggest reading about How Classpath works in Java (see the link in the first paragraph).

Summary

If you are getting "Error: Could not find or load main class XXX", where XXX is the name of your main class while running Java program then do this to solve that error:

1) If you are running Java program right from the directory where .class file is and you have CLASSPATH environment variable defined then make sure it include current directory. (dot). You can include it as set CLASSPATH=%CLASSPATH%;. in Windows and export CLASSPATH = ${CLASSPATH}:. (see the separator, in Windows it's;(semicolon) while in Linux it is (colon), also note we have included current directory in existing classpath. If you still face the issue of setting classpath, see this step by step guide to set the classpath. Same thing applies if you are running your program using -cp or -classpath option.


2) If you are running Java program from the directory, your .class file is and you don't have any CLASSPATH or -cp option then check whether your class is the in the package or not. If it's the in the package then go outside of the package directory and run java command with fully qualified name e.g. if your program is com.abc package then runs following command from the parent directory of "com"

java com.abc.HelloWorld

without any classpath hints, Java will look into the current directory and search for com\abc\HelloWorld.class in Windows, so if com directory exists in your current directory, your program will run otherwise you will get "Error: Could not find or load main class dto.HelloHP".


3) You can run your Java program from anywhere with the help of proper CLASSPATH or java -cp option as shown below:

java -cp C:\test\;. com.abc.HelloWorld


If you still facing any issue just check whether you have accidentally using CLASSPATH environment variable, you can check this in Windows by running echo %CLASSPATH% command and in Linux by running echo $CLASSPATH. If CLASSPATH is nonempty then it will print its value otherwise just echo the same command.

4) If you are running in Java version 1.6 or 1.5, then instead of receiving "Error: Could not find or load main class", you will get Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld. It's only from JDK 1.7 onward we are started receiving this new error. The solution is exactly same, every bit of discussion applies to that case as well. So if you are not able to solve that problem by following steps here, do let me know and I will try to work with you to troubleshoot the problem.

Here is the screenshot of how I tried to reproduce and solve the error as discussed in the previous paragraph:

Solution of Error: Could not find or load main class HelloWorld



That's all about how to solve "Error: Could not find or load main class HelloWorld" in Java. Classpath is little confusing topic to master, but you will understand it once you started writing and running some Java program. If you are still not able to fix your problem then post a comment there with what you have tried and we will try to troubleshoot together.

My goal is not just to give you solution but also make you able to explain why the solution is working and CLASSPATH basics are very important for a Java developer. I have seen many programmers getting frustrated, losing interest in Java due to various PATH and CLASSPATH issues e.g. NoClassDefFoundError and ClassNotFoundException and this is my humble effort to bring them back and empower with practical knowledge. Hope you understand.


Further Reading
Building debugging and troubleshooting skill is not easy and it takes lots of practice and experience to understand, reproduce and solve the error. If you are new Java developer then you first pick a book to learn Java from start to end, but if you are intermediate Java developer then you should look at the following resources to develop your debugging skill.

68 comments :

Anonymous said...

Another common cause of this error is invoking java command with .class file. Java just need name of your main class without any extension. If you call this

java HelloWorld.class

you will see
Could not find or load main class HelloWorld.class

Anonymous said...

Thank you so, so much for the thorough explanation. I was trying to figure out as to why it keep prompting that error message.

I had multiple folders/packages to compile. The compilation wasn't the issue but the running of the main file in a child directory, is. Apparently, I ran it as:

>java dto\Hello

instead of

>java dto.Hello

YoNoSe said...

Hello: Have you ever faced permissions issues on windows server 2012? Our program runs perfectly if you just double click on it, but it doesn't as a scheduled task. User is set to run wheter logged in or not. It also has full permissions on the program path and it has execution permissions on the java.exe path as well. Do you happen to have any clues on this situation? We are getting the "Error: Could not find or load main class" with the sched task user. Thanks!

javin paul said...

Hello Javier, by scheduled task do you mean running your Java program as windows service?

jaison said...

Hi, I am trying to call one c function from java via JNI. I added dll of the c program in java build path. but after doing this , i am getting the error "Could not find or load main class".
I am using Cygwin & eclipse.

c program
---------------
#include < stdint.h >
#include "JniCSidePgm.hpp"
#include < stdio.h >
#include < jni.h >

int sum(int v1,int v2){
return v1+v2;
}


java program
------------------
package com.jni;

public class JniJavaSidePgm {

static {
System.loadLibrary("JniCSide"); // Load native library at runtime
// hello.dll (Windows) or libhello.so (Unixes)
}

// Declare a native method sayHello() that receives nothing and returns void
private native void sum(int v1,int v2);

// Test Driver
public static void main(String[] args) {
new JniJavaSidePgm().sum(1,2); // invoke the native method
}
}

javin paul said...

Hello Jaison, from where did you running your program? since your main class is inside com.jni package, you must run outside that directory and provide a fully qualified name e.g.
java -cp . com.jni.JniJavaSidePgm

Anonymous said...

Running from outside the package did the job for me, thanks! No one any where else was able to get that across

Anonymous said...

Thank you! You just saved me from banging my head against the wall! I kept trying to go to Run | Run in Eclipse and in past exercises (I'm working out of the Head First Java book) I didn't have to do that. I completely forgot about the "right click" and "Run As" Java Application!

javin paul said...

@Anonymous, glad to hear that solution worked for you.

raghu said...

I am unable to compile main class and in my directory byte code is not created for the main class..

javin paul said...

@raghu, what error are you getting, can you post your error here?

Anonymous said...

thank you! you're awesome my friend! you saved me... I spent hours to find a solution for this error.

Anonymous said...

Hello, I am getting "Error: Could not find or load main class Server" on Eclipse. Server is the main class, contains main() method but somehow Eclipse is not able to find it. It's on default package, and I have tried everything from cleaning the project, building the project and build automatically. Not sure what is wrong, can you please help?

mourina said...

Hey Javin,

Thanks a lot.

Helped my solve my first Java issue.



Unknown said...

hey. I am trying to run a java program via notepad and i am using window 7 32 bit. The program is unable to run saying "Could not find or load main class". I have tried every possible thing from setting the path and classpath to using dto but the result is the same. pls help. i am using jre and jdk1.8.0_73

mithilesh said...

Hi, Is anyone available now.
I get an error while running a java program from command prompt

javin paul said...

Hello @mithilesh, what did you try? does solution given here helped you?

mithilesh said...

@Javin: Thank you for replying. I was able to execute the program but after removing the package name from the program file. How to run the program with the package name in the file?

javin paul said...

@mithilesh, you need to run the program outside of the directory e.g. if package is com then run the command outside of the com directory with full classname i.e. com.ClassName, I think I have discussed this in the article as well.

See this example

C:\Users\WINDOWS 8\workspace\Demo\target\classes>java dto.HelloHP
My first program in Java, HelloWorld !!

Unknown said...

Not working :( HELP!

Getting error: Could not find or load main class

javin paul said...

Hello @Robert, what did you try and what is not working? Can you please describe your problem in little more detail?

Valerie said...

I have a folder on my desktop called ’opennlp’ where my .class file is in.
So, I followed the instructions and in my command line returned to the desktop to run the following command:
java opennlp.OpenNlpTest

However, I still get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: opennlp/tools/util/ObjectStream
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2625)
at java.lang.Class.getMethod0(Class.java:2866)
at java.lang.Class.getMethod(Class.java:1676)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Caused by: java.lang.ClassNotFoundException: opennlp.tools.util.ObjectStream
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 6 more

I hope you can help me

Anonymous said...

Hello Mahek,try changing the name of your program to the name of the project class .It worked for me.

Anonymous said...

Thanks for this article, it was really usefull :-)

Unknown said...

You don't know how much your steps helped me to solve my problem. A big thank you Javin Paul :)

javin paul said...

your welcome @Ganesh, glad you find this tutorial useful.

Anonymous said...

This doesn't work for me. I am running Fedora (Linux). I copied your source for HelloHP and saved it as HelloHP.java. I then opened a terminal window, went to where I saved the file and compiled it from the command line. When I went to run it I got the class not found error as expected. I then went to the parent directory and tried again. Still failed. What am I doing wrong?
Here is the output from my attempt

vince@Vince2 sample]$ javac HelloHP.java
[vince@Vince2 sample]$ java HelloHP
Error: Could not find or load main class HelloHP
[vince@Vince2 sample]$ cd ..
[vince@Vince2 hsqldb]$ java dto.HelloHP
Error: Could not find or load main class dto.HelloHP

Thank you in advance

Anonymous said...

Update - I made a few changes and got it to work. I commented out the package statement in the source and added "-cp ." to the java command. This worked. What was wrong with the original code?
Here is some output:

vince@Vince2 sample]$ cat HelloHP.java

package HelloHP;
/**
* Simple Java program to demonstrate following error
* Error :Could not find or load main class
*
* @author Javin Paul
*/
public class HelloHP {

public static void main(String args[]) {
System.out.println("My first program in Java, HelloWorld !!");

}

}
[vince@Vince2 sample]$ java -cp . HelloHP
Error: Could not find or load main class HelloHP
[vince@Vince2 sample]$ javac HelloHP.java
[vince@Vince2 sample]$ java -cp . HelloHP
My first program in Java, HelloWorld !!

dArch said...

Very helpful explanation ... solved my issue w/o a fuss, thanks:-)

javin paul said...

@dArch, thanks!!glad to know that it help you to solve your issue.

Anonymous said...

Eclipse - main class not found error
I was also getting same problem in Eclipse i.e. whenever I run my program either by Run configurations or right click and run as Java program, I get the popup complaining about could not find or load main class. I debug it by debug as Java program and found that it was one of the dependent JAR which was available in classpath but Eclipse was not seeing it. My error was resolved after deleting existing run configuration where User entry was not pointing to default classpath. Just deleting the run configuration and re-creating it by running the class as right click, Run as Java program will fix the error.

Unknown said...

I get an error could not find or load main class in my code how to fix it can anyone help me

Gupta Ujjwal said...

import java.sql.*;
import java.io.*;
import java.util.*;
import java.lang.*;
class scrolldemo
{
public static void main(String args[])throws IOException,ClassNotFoundException
{
Scanner sr=new Scanner(System.in);

Connection con=null;
Statement stmt=null;
ResultSet rs=null;
int ch;

//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
try
{
//con=DriverManager.getConnection("jdbc:odbc:developer");
con=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\User\\Desktop\\db.accdb");
stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=stmt.executeQuery("select * from student");

do
{
System.out.println("1) First Record");
System.out.println("2) Last Record");
System.out.println("3) Previous Record");
System.out.println("4) Next Record");
System.out.println("5) Exit Record");
System.out.println("Enter your choice");
ch=sr.nextInt();
if(ch==1)
{
if(!rs.first())
{
rs.first();
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
else
{
System.out.println("Already on first record");
}
}
else if(ch==2)
{
if(!rs.last())
{
rs.last();
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
else
{
System.out.println("Already on last record");
}
}
if(ch==3)
{
if(rs.previous())
System.out.println(rs.getString(1)+" "+rs.getString(2));
else
System.out.println("Already on first record");
}
if(ch==4)
{
if(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
else
System.out.println("Already on last record");
}
}while(ch!=0);
rs.close();
stmt.close();
con.close();

}
catch(SQLException e)
{
System.out.println(e);
}
new scrolldemo();
}
}

I am trying to run this program but i am getting an error could not find or load main class scrolldemo.

I have saved the java file in " C:\Users\User\Desktop "

I have set the classpath as "C:\Program Files\Java\jdk1.8.0_91\jre\lib\ext" as my ucanaccess.jar file is in this folder because my OS does not support Type1 driver.

when i compile the program as "javac demo.java"
and try to run as " java scrolldemo"
I get an error "could not find or load main class scrolldemo"
I used classpath to set the ucanaccess.jar file so that i wont get an error as "ClassNotFoundException"
Please Help me.

keith said...

Your description is really great and I thought FINALLY my problem is over. Sadly not.
I'm getting really desperate... My app compiles fine with the -classpath switch under javac however if I try to run it with -cp or -classpath. I have included the compile below with the error from not having the classpath from completeness.
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
# javac JDBCQuery.java
JDBCQuery.java:71: error: package com.ibm.as400.access does not exist
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
^
# javac -classpath /usr/lib/jvm/java-8-oracle/jre/lib/jt400.jar JDBCQuery.java
#
# java JDBCQuery 172.1.1.1 PSPF PRICE
Exception in thread "main" java.lang.NoClassDefFoundError: com/ibm/as400/access/AS400JDBCDriver
at JDBCQuery.main(JDBCQuery.java:71)
Caused by: java.lang.ClassNotFoundException: com.ibm.as400.access.AS400JDBCDriver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
# java -cp /root JDBCQuery 172.1.1.1 PSPF PRICE
Exception in thread "main" java.lang.NoClassDefFoundError: com/ibm/as400/…. (same as previous)
# java -classpath /root JDBCQuery 172.1.1.1 PSPF PRICE
Exception in thread "main" java.lang.NoClassDefFoundError: com/ibm/as400/…. (same as previous)
# echo $CLASSPATH
/usr/lib/jvm/java-8-oracle/jre/lib:.
tried above with CLASSPATH unset too. Code is below, it is just trying to connect to an iSeries using the IBM jtopen 9.1 tool:
import java.sql.*;
public class JDBCQuery
{
public static void main (String[] parameters)
{
Connection connection = null;
try {
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
connection = DriverManager.getConnection ("jdbc:as400://" + system);
DatabaseMetaData dmd = connection.getMetaData ();
Statement select = connection.createStatement ();
ResultSet rs = select.executeQuery (
"SELECT * FROM " + collectionName + dmd.getCatalogSeparator() + tableName);
ResultSetMetaData rsmd = rs.getMetaData ();
while (rs.next ()) {
for (int i = 1; i <= columnCount; ++i) {
String value = rs.getString (i);
if (rs.wasNull ())
value = "";
System.out.print (format (value, columnWidths[i-1]));
System.out.print (" ");
}
System.out.println ();
}
}
catch (Exception e) {
System.out.println ();
System.out.println ("ERROR: " + e.getMessage());
}
finally {
try {
if (connection != null)
connection.close ();
}
catch (SQLException e) {
// Ignore.
}
}
System.exit (0);
}
}
If I don't include any of the connection information the script outputs the error messages correctly (removed due to char limit) so it looks to me that it has an issue with the JTOpen driver. Any help would be GREATLY appreciate.
# ls -lh /usr/lib/jvm/java-8-oracle/jre/lib/jt400.jar
-rwx------ 1 root root 4.6M Feb 12 18:28 /usr/lib/jvm/java-8-oracle/jre/lib/jt400.jar

Anonymous said...

Finally explained well, whithout a stupid advice to set classpath environmental variable for simple programs. Thank you a lot!

Revolper said...

It was really useful, thank u :)

Nikita said...

Great Explanation. I tried to run java program from command line but i am still getting the same issue.
Project structure:
example/Snippet.java
example/org.json.jar

I've to include the jar in classpath and i'm executing the program from example directory.(Running from Linux terminal)
javac -cp ./org.json.jar Snippet.java
java -cp ./org.json.jar:. Snippet

javin paul said...

Hello @Nikita, did you able to run the program from command line or you still have some error?

Anonymous said...

Thank you for this page, and related help. It helped me a lot as beginner. !

javin paul said...

@Anonymous, glad that this tutorial helped you to solve your problem.

Unknown said...

java and javac cmd are working properly on normal cmd line so it shows that environment variable is working properly but when i run any programthen it can compile only and make a byte code but i cannot run this class file via javac tool.it shows Error: Could not find or load main class.plz resolve this problem send your response on gauravlodhi41@gmil.com.

Unknown said...

Hello, I have followed your blog and I am still facing the same issue.
Please Assist me on https://stackoverflow.com/questions/49738153/java-cannot-load-or-find-main-class or assist me here.

javin paul said...

Hello Jesse, Can you share how you are running your program in Eclipse? What have you put as Main Class etc?

SANGWA said...

i still get the same error, the app runs in netbeans but not in dist folder

Unknown said...

Hi, I am getting 'error: could not find or load main class' when I am trying run a java program with multiple classes, but it is working fine with a single class. What might be the reason for this?

Ubuntu Cinnamon said...

I don't know how I didn't know this as an expert java developer

Unknown said...

Thanks, this article is really problem-solving for me

Anonymous said...

class exceptionDeom2
{
public static void main(String args[])
{
try{
System.out.println(3/0);
System.out.println("in try");
}
catch(ArithmeticException e){
System.out.println("Exception"+e.getMessage());
}
/* finally{
System.out.println("learning Exception Handeling");
}*/
}
}
Error:-
E:\java\Java_Programs\Exception handling> java exceptionDemo2
Error: Could not find or load main class exceptionDemo2
PS E:\java\Java_Programs\Exception handling>

Anonymous said...

Thank you. You are awesome!!

Anonymous said...

I Created a JavaFX Application with BlueJ. The Appplication compiles and runs as expected with BlueJ. However, When I create a Jar File of the application and try to run it by double clicking, Nothing Happens. When I run it using CMD it displays an error
"Error: Could not find or load main class".
I even tried Wrapping the Jar in an .exe file using Launch 4J with the same results. I am frustrated I have spent a week trying to figure this out. I have read thousands of online fixes including this and I cant seem to find the solution.

My Objective is create a standalone .exe file which I can then share with a friend or run on any windows machine.
please help.

Unknown said...

I was looking for solution on this issue for over 3 hour , only now its work by your suggestions , after adding the environment variable
CLASSPATH=%CLASSPATH%;.

Thanks for great explanation

Juliano said...

When I build my .jar file once I try to java -jar I get hte following "Javassist version 3.22.0-GA
Copyright (C) 1999-2017 Shigeru Chiba. All Rights Reserved." while if I run with java -cp test.jar com.test.boot.Mainkt I get correct execution. Any suggestion for me to be able to run my jar file as java -jar test.jar

Anonymous said...

Thanks Man, You saved my day. Thanks a lot

Anonymous said...

Even without any package one can get this error.
The note touches upon this by saying CLASSPATH=%CLASSPATH%; must be there to include the current directory.
I got this error when I just used
set classpath=c:\Java\jdk1.8.0_211;c:\Json\json-simple-1.1.1.jar
The above will not pick a class from the current directory )c:\Json)

set classpath=;C:\Java\jdk1.8.0_211;c:\Json\json-simple-1.1.1.jar - solved it
or better to use

set classpath=%CLASSPATH%;C:\Java\jdk1.8.0_211;c:\Json\json-simple-1.1.1.jar

Anonymous said...

Thank you for this help. Within Eclipse, no problem running my Java with Package. Using your help above was able to run my Java classes without a Package from the command line, but not Java classes with Package. Solved issue by copying my .java to Notepad and deleting top Package line and Save, then recompiling with javac. It worked! Thanks again.

javin paul said...

Great to hear that @Anonymous

Invoice control de facturas said...

Yo lo resolví así y con la siguiente configuración de CLASS_PATH y path.
W10 64
Open Java jdk-13.0.1
Apache Netbeans 11.2

JAVA_PATH = C:\JavaOpen\jdk-13.0.1\
PATH = %JAVA_PATH%\bin\

En el CMD, entrar a la carpeta ...\target\classesy ahí llamar a la clase main del programa, ejemplo :
...\target\classes>java openjava.holamundo.inicio

(En mi proyecto la ruta de salida es:
C:\Users\Usuario\Documents\NetBeansProjects\holaMundo\target\classes\openjava\holamundo)

Y listo! funciona!

RG said...

Thanks for the good article.

In the article echo %CLASSPATH should be echo %CLASSPATH% in windows 10 home from the command line.

Juan Jesus said...

Thank you for the explanation, Javin!

Anonymous said...

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class ClickableDice extends Applet implements MouseListener {

int die1 = 4; // The values shown on the dice.
int die2 = 3;


public void init() {
// To initialize the applet, register the applet to listen
// for mouse events on itself. Also set a light blue
// background color.
addMouseListener(this);
setBackground( new Color(200,200,255) );
}


public void paint(Graphics g) {
// The paint method draws a blue border and then
// draws the two dice.
g.setColor( Color.blue );
g.drawRect(0,0,99,99);
g.drawRect(1,1,97,97);
drawDie(g, die1, 10, 10);
drawDie(g, die2, 55, 55);
}


void drawDie(Graphics g, int val, int x, int y) {
// Draw a die with upper left corner at (x,y). The die is
// 35 by 35 pixels in size. The val parameter gives the
// value showing on the die (that is, the number of dots).
g.setColor(Color.white);
g.fillRect(x, y, 35, 35);
g.setColor(Color.black);
g.drawRect(x, y, 34, 34);
if (val > 1) // upper left dot
g.fillOval(x+3, y+3, 9, 9);
if (val > 3) // upper right dot
g.fillOval(x+23, y+3, 9, 9);
if (val == 6) // middle left dot
g.fillOval(x+3, y+13, 9, 9);
if (val % 2 == 1) // middle dot (for odd-numbered val's)
g.fillOval(x+13, y+13, 9, 9);
if (val == 6) // middle right dot
g.fillOval(x+23, y+13, 9, 9);
if (val > 3) // bottom left dot
g.fillOval(x+3, y+23, 9, 9);
if (val > 1) // bottom right dot
g.fillOval(x+23, y+23, 9,9);
}


void roll() {
// Roll the dice by randomizing their values. Tell the
// system to repaint the applet, to show the new values.
// Also, play a clicking sound to give the user more feedback.
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
play(getCodeBase(), "click.au");
repaint();
}


public void mousePressed(MouseEvent evt) {
// When the user clicks the applet, roll the dice.
roll();
}


public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }


} // end class ClickableDice


Can you solve this errors in my program

Unknown said...

still not able to overcome with this problem.

javin paul said...

@Unknown, can you provide more details about your situation, may be we can guide you in the right direction.

Anonymous said...

import java.util.*;
class Student
{
int rno;
String name;
void info()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student ");
name = sc.next();
System.out.println("Enter the Roll no. ");
rno = sc.nextInt();
}
}

class Test extends Student
{
int mrk1,mrk2;
public void mrks()
{
Scanner m = new Scanner(System.in);
System.out.println("Enter the marks of 1st subject ");
int m1 = m.nextInt();
System.out.println("Enter the marks of 2nd subject ");
int m2 = m.nextInt();
mrk1 = m1;
mrk2 = m2;
}
public void display()
{
System.out.println("Name of the student:- " + name);
System.out.println("Roll no. of the student:- " + rno);
System.out.println("Marks of 1st subject:- " + mrk1);
System.out.println("Marks of 2nd subject:- " + mrk2);
}
public static void main(String args[])
{
System.out.println("B227 KK");
Test te = new Test();
te.info();
te.mrks();
te.display();
System.out.println("B227 KK");
}
}


I am getting a error in this program

lakshmi Naresh said...

awww it got worked for me, like below
- cd ..
- java firstPackage.HelloWorld

Anonymous said...

Hello,thank you for your help. It was really usable. One question: if I open my JAR file (already compiled) in the Command Prompt, it works, but if I open it directly from a folder in Windows, it doesn't show errors but quickly exits. Why?

javin paul said...

It depends how are you opening? if you use winrar or winzip, you can see class files inside JAR on Windows.

Anonymous said...

Literally thank you so much

Dinesh said...

Nice help regarding setting of classpath variable in various ways. Thank you so much for wrining this article.

Post a Comment