Reputation: 43
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??
Upvotes: 4
Views: 37889
Reputation: 11
I got the same errors in my project when I started my app from a different vscode folder.
In the end, the problem turned out to be with the run button of VSCode (top right). It was set to "Run Code" by default instead of "Run Java" when I open a new folder in VSCode that I haven't opened before.
Upvotes: 0
Reputation: 21
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
Upvotes: 2
Reputation: 2178
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 :
.
Upvotes: 7