Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: package does not exist

Tags:

java

I am in the directory: E:\stuff\Java>

I created a package A:

package pack;

public class A
{
    public void methodA(){
        System.out.println("MethodA");
    }
}

To compile I have used the following statement:

javac -d . A.java

So a folder with the name pack has been created which contains A.class. Then i tried to import this package in another program:

import pack.A;

    class B
    {
        public static void main(String[] args){
            A a = new A();
            a.methodA();
        }
    }

When i try to compile this code:

javac B.java

I get the following error:

   B.java:1: error: package pack does not exist
import pack.A;
           ^
B.java:6: error: cannot find symbol
                A a = new A();
                ^
  symbol:   class A
  location: class B
B.java:6: error: cannot find symbol
                A a = new A();
                          ^
  symbol:   class A
  location: class B
3 errors

I don't understand why the code fails to run. My B.java file and pack are in the same folder.

Can someone please explain the error in this code??

like image 681
Talluri Raviteja Avatar asked Sep 15 '25 13:09

Talluri Raviteja


2 Answers

From your error it looks like your "other program" B.java is not in the same directory (E:\stuff\Java) of 'A.java'. This means that when you try to compile B.java the compiler does not know where to find class pack.A. To "make A visible" you must add pack.A to your classpath, which means compiling with:

javac -cp ".;<path_to_add>" B.java

In your case <path_to_add> should be E:\stuff\Java. This sets your classpath to not only the current directory (.) but also the directory where your pack package is.

To run your program you again have to add pack.A to you class path:

java -cp ".;<path_to_add>" B

Where again <path_to_add> should be E:\stuff\Java.

Here I am assuming you are using windows. On Unix the -cp option as a slightly different syntax: -cp ".:<path_to_add>" where the ; has been replaced by :.

like image 152
mziccard Avatar answered Sep 17 '25 04:09

mziccard


Try out the following command to compile the program on windows :

 javac -cp "<path of the package folder>" file_name.java

And the command to execute the program :

java -cp "<path of the package folder>" file_name
like image 30
user12893276 Avatar answered Sep 17 '25 03:09

user12893276