import - How to compile dependent .java files located in different packages -
i have folder named pack, inside there 2 folders p1 , p2.
inside folder p1 write following code in file named sum.java
package pack.p1; public class sum{ public static void display_sum(int a,int b){ system.out.println("sum = "+(a+b)); } }
then inside folder p2 write following code in file named wap8.java
package pack.p2; import pack.p1.sum; import java.util.scanner; class wap8{ public static void main(string args[]){ scanner s=new scanner(system.in); system.out.println("enter 2 no.s = "); int a=s.nextint(); int b=s.nextint(); sum.display_sum(a,b); } }
here flow of execution in cmd prompt. first create class file of sum.java executing
h:\java\wap 4\pack\p1>javac sum.java
then set classpath sum as
h:\java\wap 4\pack\p1>set classpath=%classpath%;h:\java\wap 4\pack;
then in cmd line come folder p2 , execute following, shows package pack.p1 doesnt exist. why so??
h:\java\wap 4\pack\p2>javac wap8.java
wap8.java:2: error: package pack.p1 not exist
import pack.p1.sum;
^
wap8.java:10: error: cannot find symbol
sum.display_sum(a,b);
^
symbol: variable sum
location: class wap8
2 errors
i tried setting classpath vairable in environment variables variable name classpath , variable value h:\java\wap 4\pack;. still not working when execute javac wap8.java , showing same error above
you overly complicating things no reason. use following steps , should good.
- navigate
h:\java\wap 4\pack\p1
directory. javac sum.java
- navigate
h:\java\wap 4\
directory. javac pack\p2\wap8.java
that's it. no need setting classpath
explicitly. reason why have compile wap8
wap 4
folder because package statement in class binds qualified name. sum1
has fqn pack.p1.sum
, wap8
has fqn pack.p2.wap8
. therefore, javac
won't able see pack.p1.sum
when in pack\p2
folder.
you can run code h:\java\wap 4
directory using java pack.p2.wap8
Comments
Post a Comment