Home > Software design >  Unable to run java program from commandline
Unable to run java program from commandline

Time:03-06

I am having serious trouble with running a java program from the commandline. I feel I am so close to having figured out whats wrong, but I'm just at a loss, and I need help.

I'm trying to run a simple Hello World program (in VSCode on windows, using bash terminal) with the following commands:

javac Hello.java

java Hello

This simply doesn't work, however, writing the full path to the file does work, so something like this works.

javac -cp c//path//to//file// Hello.java

java -cp c//path//to//file// Hello

Also, running the file with F5 also works fine. I would like to run my program with command line arguments, and not have to write the entire path to the file every time, as it is very tedious.

My PATH and CLASSPATH variables are as follows:

PATH: C:\Program Files\Eclipse Adoptium\jdk-17.0.2.8-hotspot\bin

CLASSPATH: C:\Program Files\Eclipse Adoptium\jdk-17.0.2.8-hotspot\bin

Could anyone give me some insight as to what is wrong? The closest solution I've found to reduce the amount I have to manually write is to save a variable in my .bashrc to my current working directory, making the following command possible:

java "$cwd"Hello

Any help is greatly appreciated.

CodePudding user response:

Your CLASSPATH is broken.

CLASSPATH as a concept is where java class files (or jars with the class files inside them) live. Not where the java binaries are (java generally knows where they are. For the few tools that do not, JAVA_HOME is for that, and you provide the 'home dir' (the parent of that bin dir).

Java knows where to find its own core classes (such as java.lang.String and co), these are provided by the bootclasspath.

Generally, you don't want to use CLASSPATH as an environment variable in the first place: You can have more than one java project on a single computer, with completely different needs. That's why IDEs, build tools, and java -jar completely ignore that variable.

However, it is the answer for making just plain ole javac *.java; java MyClass work. Specifically, you should set CLASSPATH to: "."

That's it. Just dot: The current directory. Once you've done this, you can simply type:

javac MyApp.java
java MyApp

Note that with modern java versions, you can actually just write java MyApp.java; java will compile and run your code in one go. This will fail to work real fast (when you involve dependencies and multiple packages), but for the most academically simple case of a single source file, that works fine too.

Note that "$PWD" just works, out of the box.

CodePudding user response:

Are you sure you are in the specified directory? If not, navigate to it using cd.

  • Related