Lee Baldwin
Lee Baldwin

Reputation: 39

Issues with CLASSPATH in Java

I have an issue with setting up my Java dev environment. In the past,I have installed Java, then my IDE and went to coding. I am now starting to setup my laptop to use command-line compiling and Notepad as my code editor. I am getting an error that I have tried to correct, but since this is my first time doing it this way, I am kinda lost.

I run javac and it creates my .class file with no issue, but then I try to run the class file with the java A and it throws an error:

c:\workspace>java A Error: Could not find or load main class A Caused by: java.lang.ClassNotFoundException: A

My CLASSPATH is set to C:\Program Files\Java\jdk-14.0.1\lib

My code is:

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

Thanks in advance for any help.

Upvotes: 0

Views: 1332

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103773

Using global environment variable CLASSPATH is a very bad idea. It's possible to write more than one java program on a single machine, you know :)

To compile the code, javac A.java will do the job. To run it, assuming the A class has no package statement, the directory that contains the class file needs to be on the classpath. By default, the classpath is configured to basically be '.', as in, the current directory. If you messed with it, well, you broke that. You shouldn't mess with that environment variable.

The fix is to specify classpath manually every time you invoke java, or, use build systems that take care of this for you:

java -cp . A

will work fine, as long as you're in the directory containing A.class.

Upvotes: 2

Related Questions