-1

In the directory:

/home/ThinkPinkApp/flocks

I have the following two source files:

FlockingInformation.java FlockLists.java

at the top of each source file I have

package home.ThinkPinkApp.flocks

Compiling the files causes no issue, however, when I attempt to run the main methods for each file, I receive the following error:

Error: Could not find or load main class FlockingInformation Caused by: java.lang.NoClassDefFoundError: home/ThinkPinkApp/flocks/FlockingInformation (wrong name: FlockingInformation)

Compiling and running the files in my home directory ~/ThinkPinkApp/objects without the package keyword is fine and causes no issue. When I add package objects to the same sources files in my home directory though I receive the same error.

I have attempted to use the -CLASSPATH option with the java command, and still receive the same error. I have read the official oracle documentation regarding the java command and am unsure of what I am doing wrong. My understanding is that the JVM looks for files in the current directory by default, so why isn't it able to find/load these classes? I understand that the JVM also uses the class path variable, but I am unsure how to access/change that. and even then I should be able to use the -cp option to manually change what directories it looks in right?

I have also attempted running the files with java home.ThinkPinkApp.FlockingInformation this produces a similar error, minus the (wrong name: FlockingInformation) part. Unsure of what this means though.

Any explanation or suggestions would be greatly appreciated.

1 Answers1

0

Broadly, Java sources and classes need to be stored in such a way that the directory hierarchy matches the package hierarchy. If you want to run class home.Foo, the class file must be in a directory home. Then either the current directory should be the one that contains home, or $CLASSPATH needs to reference the directory that contains home.

Using the -d switch to javac will control the directory where compiled classes are written. When this switch is given, the directory structure will automatically be created so that it matches the package structure, so you shouldn't need to fiddle about moving the .class files around manually.

There's a detailed discussion of these issues here:

What does "Could not find or load main class" mean?

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15