Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java running a program at command prompt: could not find or load main class

I am trying to learn how to compile and run using only command lines in Windows. Here is the tree of the directories starting from the root:

D:
 ActivityOne
     - classes
         - com
           -wat
             -sampleapp
                -students
                    StudentE.class
                 StudentMasterList.class (Main)
     - src
         -com
           -wat
             -sampleapp
                -students
                    StudentE.java
                 StudentMasterList.java (Main)

The thing is that I am now confused as to how to run the program. I tried two things, where both returned different errors.

1st try:

java -classpath classes StudentMasterList

returned:

Error: Could not find or load main class StudentMasterList

2nd try:

java -classpath classes/com/wat/sampleapp StudentMasterList

returned:

Exception in thread "main" java.lang.NoClassDefFoundError: StudentMasterList (wrongname: com/wat/sam
pleapp/StudentMasterList)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

I got confused after the next tries, any help on how i should run the main class?

Update: I should run all my commands at the ActivityOne level.

like image 542
Jer Yango Avatar asked Feb 16 '23 01:02

Jer Yango


1 Answers

The correct way is

java -classpath D:\ActivityOne\classes com.wat.sampleapp.StudentMasterList

In other words, you add the top-level directory to the classpath, and then use the fully-qualified name of your Java class.

like image 151
NPE Avatar answered Apr 26 '23 06:04

NPE