poetic crayons
poetic crayons

Reputation: 55

executing java program from command line in windows fails

I'm trying to run a very simple one class "Hello World" program from the command line in Windows.

The .java file is located at "C:\Users\UserName\Desktop\direcName". The package is deem and the class name is test.

I can cd to the directory and compile it from there using javac test.java and that works perfectly fine. However, when I try to run it using:

java test or java -classpath directory test or java -cp . test it throws "Exception in thread main java.lang.NoClassDefFoundError: test (wrong name: deem/test).

If I use java deem.test it says: Error, could not find or load main class deem.main

How can I fix the exception and get my program to run?

Thanks

Upvotes: 1

Views: 2384

Answers (2)

Stephen C
Stephen C

Reputation: 718768

This is a variation of the "common beginners error" with running Java programs from the command line.

java test or java -classpath directory test or java -cp . test it throws "Exception in thread main java.lang.NoClassDefFoundError: test (wrong name: deem/test).

The JVM is in effect telling you that found "test.class" on the search path, but when it read class file, it concluded that the file should have been at "./deem/test.class" or "directory/deem/test.class" ... depending on which "-cp" / "-classpath" argument you actually used

If I use java deem.test it says: Error, could not find or load main class deem.main

This is now telling you that it cannot find "deem/main.class".

Note that you have now told it to look for a class called "deem.main" instead of "test" or "deem.test". (Or perhaps you just transcribed something incorrectly there.)

The rules are really rather simple:

  1. You must give the fully qualified class name to java as the first argument after the options. (Not the simple class name. Not the ".class" file name. Not the name of the entry point method.)
  2. You must specify the classpath such that the java command can
    • map the class name into a relative pathname for the class file (e.g. foo.bar.baz.MyClass maps to foo/bar/baz/MyClass.class) ...
    • and then resolve that relative path against one of the classpath entries; e.g. if . is the classpath, then ./foo/bar/baz/MyClass.class.
  3. The class must have the required public static void main(String[]) entry point method.

So IF ...

  1. the fully qualified class name of your class is deem.test; i.e. the test class is in the package deem, AND
  2. the corresponding class file is in ./deem/test.class, AND
  3. it has the required entry point method, AND
  4. the test application doesn't depend on other classes of yours or 3rd party libraries ...

THEN java -cp . deem.test should work.

Upvotes: 5

Austin
Austin

Reputation: 4929

If the class is located in a package "deem", then you need to include the package name like this.

java deem.test

That should work.

Upvotes: 1

Related Questions