Search code examples
javajavac

Why I am getting package not found error?


I have created two java files A.java and B.java. Both classes are in same folder testjava.

Code in A.java

package pkg;

public class A{
    int data;
    public void printer(){
        System.out.println("I'm in A");
    }
}

Code in B.java

package mypkg;
import pkg.*;

public class B{
    void printer(){
        System.out.println("I'm in B");
    }
    public static void main(String[] args){
        A obj = new A();
        obj.printer();      
    }
}

To compile first file I used: javac -d . A.java which compiled with no errors and created A.class in ./pkg folder
To compile second file I am using javac -cp "./pkg" B.java which gives me the following errors: Error Image

My directory structure after compilation of A.java: After A.java compilation

What should include as my classpath? I have read and tried other StackOverflow questions on the same topic but couldn't solve my problem.


Solution

  • Assuming your project directory looks like this:

    project| tree
    .
    ├── mypkg
    │   └── B.java
    └── pkg
        └── A.java
    
    

    you should compile A like this:

    javac pkg/A.java
    

    and B with

    javac mypkg/B.java
    

    you should do this from the project directory. After you compile, the directory structure looks like this:

    project| tree
    .
    ├── mypkg
    │   ├── B.class
    │   └── B.java
    └── pkg
        ├── A.class
        └── A.java
    

    BTW, you have a syntax error in your code, should be obj.printer(); instead of A.printer();.