Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not find main class HelloWorld

Tags:

java

I installed Java 1.7.0 in the following folder C:\Program Files\Java. My operating system is Windows XP(Version 2002) with Service pack 3.

The environment variables which I set are:

  • CLASSPATH : C:\Program Files\Java\jdk1.7.0\jre\lib\rt.jar;

  • Path : C:\Program Files\Java\jdk1.7.0\bin;

  • JAVA_HOME : C:\Program Files\Java;

I have presented here the class names which are in my system.

Next I wrote a program, HelloWorld.java:

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

When I am compiling using javac HelloWorld.java it is compiling fine.

But after I issue java HelloWorld I am encountering the below error:

Error: Could not find main class HelloWorld Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld         at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:198)  Caused by: java.lang.ClassNotFoundException: HelloWorld         at java.net.URLClassLoader$1.run(URLClassLoader.java:299)         at java.net.URLClassLoader$1.run(URLClassLoader.java:288)         at java.security.AccessController.doPrivileged(Native Method)         at java.net.URLClassLoader.findClass(URLClassLoader.java:287)         at java.lang.ClassLoader.loadClass(ClassLoader.java:422)         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:325)         at java.lang.ClassLoader.loadClass(ClassLoader.java:355)         at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:195) 

After a bit of searching around, I found that may be something wrong in the environment variable. I tried to play with that but no luck.

I even RESTARTED the machine and then again I tried to run but with same fate.

like image 922
Newbie Avatar asked Jun 09 '10 11:06

Newbie


People also ask

Could not find or load main class means?

When you get the message "Could not find or load main class ...", that means that the first step has failed. The java command was not able to find the class. And indeed, the "..." in the message will be the fully qualified class name that java is looking for.

Could not find main class program will exit?

There are two ways to do it: Reinstall the new JRE. It should then fix the file association in the OS. Fix the file association manually.


Video Answer


2 Answers

Tell it where to look for you class: it's in ".", which is the current directory:

java -classpath . HelloWorld 

No need to set JAVA_HOME or CLASSPATH in this case

like image 50
unbeli Avatar answered Sep 20 '22 22:09

unbeli


You are not setting a classpath that includes your compiled class! java can't find any classes if you don't tell it where to look.

java -cp [compiler outpur dir] HelloWorld 

Incidentally you do not need to set CLASSPATH the way you have done.

like image 31
Sean Owen Avatar answered Sep 20 '22 22:09

Sean Owen