I have compiled the java codes with
razrlele@OVO:~/workspace/javastudy/src$ javac Helloworld.java
and it turns out no errors or warnings
then I run the program with
razrlele@OVO:~/workspace/javastudy/src$ java Helloworld
it returns this
Error: Could not find or load main class Helloworld
I have to input like this
razrlele@OVO:~/workspace/javastudy/src$ java -cp ./ Helloworld
so that the program will run correctlly.
I am confused about why the "java" command doesn't work.
Here is my /etc/environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/jdk1.8.0_11"
CLASSPATH=/usr/lib/jvm/jdk1.8.0_11
JAVA_HOME=/usr/lib/jvm/jdk1.8.0_11
Java will attempt to use your classpath to locate the class files. Since your classpath is set to /usr/lib/jvm/jdk1.8.0_11
, that's where it looks.
By overriding the classpath with -cp ./
, you tell it to look in the current directory for its class files.
There are a number of ways to fix this, including changing your classpath environment variable to include .
or other localised paths as needed. I tend to prefer just setting up an alias (in my .bashrc
for example) so regular Java programs aren't affected, something like (from memory):
alias jhere="java -cp $CLASSPATH:."
then I can just use:
jhere HelloWorld
to test my snippets.
Because .
isn't in your CLASSPATH
, first
export CLASSPATH="/usr/lib/jvm/jdk1.8.0_11:."
then
javac Helloworld.java
java Helloworld
It's also possible to use -cp
(which is short for -classpath
) with java
at the command line, if you run java -h
you will see
-cp <class search path of directories and zip/jar files> -classpath <class search path of directories and zip/jar files> A : separated list of directories, JAR archives, and ZIP archives to search for class files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With