Home > Blockchain >  Java runs in eclipse and will compile, but wont execute on cmd, but still runs in eclipse. How can I
Java runs in eclipse and will compile, but wont execute on cmd, but still runs in eclipse. How can I

Time:04-28

So I have a basic hello world set up in eclipse and I can compile it using cmd easily (I have set all the necessary paths), however when I then try to use the java command to execute the hello world, it always returns the same error: Error: Could not find or load main class helloWorld Caused by: java.lang.NoClassDefFoundError: net/codejava/helloWorld (wrong name: helloWorld)

This is the code used:

package net.codejava;

public class helloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World");
    }

}

I am cd in the right directory (I think, I cd into the src directory and then into the package file stored in src) and am using Windows 10 with java 18.0.1 and JRE build 18.0.1 10-24

Any help would be greatly appreciated, as this is highly frustrating, when the code runs effortlessly on the eclipse console. Thanks.

CodePudding user response:

Your file has a 'package' of net.codejava and a name of helloWorld, meaning, the full name of this class is net.codejava.helloWorld.

The java command, at least in the way you're using it, requires that you pass the full name, thus, you must run java net.codejava.helloWorld. Just java helloWorld simply isn't going to work.

But that's not all.

Java needs to then find the class file that contains the code for class net.codejava.helloWorld. It does this by first turning that full name into a path of sorts: net/codejava/helloWorld.class, and it will then scan each entry in the classpath for that. You can put directories and jar files on the classpath.

Thus, you have a directory on your system; let's call this directory X. X contains a directory named net, which contains a directory named codejava, which contains a file named helloWorld.class. If there is no such X (i.e. your class file is not in a dir named codejava for example), you're going to have to fix that by making these directories.

Then, X (and not the codejava dir!) needs to be on the classpath. Usually (it depends on how you configured things), 'the current dir' is by default on the classpath.

Given that your code is in, say, /home/PythonSux/workspace/learningjava/net/codejava/helloWorld.class, that means the dir that needs to be on the classpath is /home/PythonSux/workspace/learningjava. After all, if you, from there, look for net/codejava/helloWorld.class, you find the right file.

Therefore, either cd to that directory, or run java -cp /home/PythonSux/workspace/learningjava net.codejava.helloWorld

Note that this isn't usually how you actually run java apps. You either run them from your IDE, or you ask your build tool to run it, or you package your java app into a jar file and run that, etcetera.

  • Related