Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't run java prorgram with "java" command directly

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                                                                                      
like image 788
razrLeLe Avatar asked Feb 13 '23 03:02

razrLeLe


2 Answers

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.

like image 81
paxdiablo Avatar answered Feb 15 '23 09:02

paxdiablo


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.
like image 20
Elliott Frisch Avatar answered Feb 15 '23 09:02

Elliott Frisch