0
votes

I created little HelloWorld example and I am having problem running it from command prompt (on Windows). When I attempt to run it by:

java tcpServer from command prompt I get NoClassDefFoundError
I am able to compile it with javac, and class file gets generated.

Somewhere I was reading that I have to put path to my class folder into CLASSPATH environment variable. I've done it and rebooted machine, but I still get the same error.

I also was trying to run it by java -cp c:\MyFolderWhereClassFileIs HelloWorld, it doesn't work.

I've looked into ENV variables and I have following: JAVA_HOME: C:\Program Files (x86)\Java\jdk1.6.0_26; JRE_HOME:C:\Program Files (x86)\Java\jre6; CLASSPATH: C:\HelloWorld;

So, how do I run this? Any ideas how to resolve this? Thanks.

PS. The most annoying thing to me is, if I create java project in eclipse, and create HelloWorld example, then it runs fine...

UPDATE:

Here is the code. It does have package specified.

package test.com;
public class HelloWorld {
    public static void main(String[] args) {
        System.out.print("Hello World");
    }
}

My HelloWorld.java and HelloWorld.class files are here: C:\workspace\TestApp\src\test\com

One thing I learned so far is that I can't run it from within com folder or test folder. I have to be in src folder class file can be found... but I am still not able to run it... always the same error.

1

1 Answers

2
votes

Does your class have a package name? That is, a statement at the top which reads

package <mypkgname>;?

If so, then you have to (A) create the correct directory structure and (B) prefix the class name with the package name in your java command.

For example, if your Java file looks like this:

package hello;
public class HelloWorld {
    ...
}

Then a basic directory structure would resemble:

src/hello/
src/hello/HelloWorld.java
src/hello/HelloWorld.class

And your bash command would be:

cd src
java hello.HelloWorld

Otherwise, if your class has no package name, it will be placed in the default package. In this case, you simply have to cd to the directory where your class file resides, and run java HelloWorld.