Overv
Overv

Reputation: 8519

Class is found on class path when compiling, but not when running

I've written a Java class which implements an interface specified in another directory. I compile the application like this:

javac ArrayQueue.java -cp QueueArray

The class ArrayQueue implements the interface Queue in directory QueueArray. Without the specified classpath, the compiler will throw an error as expected.

However, when running the program after that, it can't find the class anymore:

java ArrayQueue -cp QueueArray
Exception in thread "main" java.lang.NoClassDefFoundError: Queue

What could possibly be causing this?

Edit: The program works fine if I copy the .class files to the same directory as ArrayQueue.class.

Upvotes: 0

Views: 222

Answers (2)

Perception
Perception

Reputation: 80633

This may be of help. From the JLS, 3rd edition:

An implementation of the Java platform must support at least one unnamed package; it may support more than one unnamed package but is not required to do so. Which compilation units are in each unnamed package is determined by the host system.

In implementations of the Java platform that use a hierarchical file system for storing packages, one typical strategy is to associate an unnamed package with each directory; only one unnamed package is observable at a time, namely the one that is associated with the "current working directory." The precise meaning of "current working directory" depends on the host system.

It would appear that the JVM you are using does not support default packages unless they are associated with the current directory, aka the directory from which you are launching your customized queue class.

In general, its a bad idea to use default packages, my advice would be to associate both classes with a package, recompile, and retest your code.

Upvotes: 1

c.pramod
c.pramod

Reputation: 606

use java -classpath . class_having_main_method

Upvotes: 0

Related Questions