javaclasspathclassnotfoundexception

how is Classpath decided in java? what makes a valid classpath?


I understood how the classpath is necessary for running the project but I still have some doubt.

I compiled my class using

javac /Users/username/IdeaProjects/leetcodePrograms/src/problems/HouseRobberII213.java

after compiling, I did

java -cp /Users/username/IdeaProjects/leetcodePrograms/src/  problems.HouseRobberII213

this runs my program

but If I do

java -cp /Users/username/IdeaProjects/leetcodePrograms/  src.problems.HouseRobberII213 

This gives

Error: Could not find or load main class src.problems.HouseRobberII213
Caused by: java.lang.NoClassDefFoundError: src/problems/HouseRobberII213 (wrong name: problems/HouseRobberII213)

Someone pls explain why this issue. How was /Users/username/IdeaProjects/leetcodePrograms/src/ decided as valid classpath but not /Users/username/IdeaProjects/leetcodePrograms


Solution

  • The class path is not invalid. It's just that there is no class called src.problems.HouseRobberII213 at the class path.

    In HouseRobberII213.java, you have probably written the package declaration as:

    package problems;
    

    This means the fully qualified name of the class is problems.HouseRobberII213, not src.problems.HouseRobberII213.

    If you had written

    package src.problems;
    

    Then there would indeed be a class called src.problems.HouseRobberII213.