Nn Karthik Nn Karthik - 4 months ago 8
Java Question

how to compile and run two different java programs with instances of one in another which are in different directories?

my first java program is

import java.io.*;
class pgm10a
{
public static void main(String args[])
{
pgm10b b=new pgm10b();
b.display();
}
void display()
{
System.out.println("A class");
}
}


it is saved in C:\NNK\pack1
the second program is

import java.io.*;
class pgm10b
{
void pgm10b()
{
pgm10a a=new pgm10a();
a.display();
}
void display()
{
System.out.println("Class B");
}
}


it is in C:\NNK\pack2
I want to run pgm10a but it keeps showing pgm10b not found exception. i have set the class path and compiled for both and both are compiled successfully. but when i try to run them it shows pgm10b not found.

enter image description here

VGR VGR
Answer

Have a look at the syntax for the java command:

java [options] classname [args]

Anything after the class name is not an option to the java command—it is simply passed as is, in a String array, to the program’s main method.

You can solve your problem by changing your final command from this:

java pgm10a -cp C:\NNK\pack2

to this:

java -cp .;C:\NNK\pack2 pgm10a

The classpath is a sequence of directories, separated by ; when running in Windows (: on other operating systems), which tell the java command where to find compiled classes. If you only specify C:\NNK\pack2, Java will only be able to see classes in that directory. The period (.) refers to the current directory, so the above classpath is pointing to both the current directory (which contains pgm10a) and the pack2 directory (which contains pgm10b).