Tuesday, November 11, 2008

Finding Packages and CLASSPATH

Finding Packages and CLASSPATH:

 

As just explained, packages are mirrored by directories. This raises an important question: How does the Java run-time system know where to look for packages that you create? The answer has two parts. First, by default, the Java run-time system uses the current working directory as its starting point. Thus, if your package is in the current directory, or a subdirectory of the current directory, it will be found. Second, you can specify a directory path or paths by setting the CLASSPATH environmental variable.

 

For example, consider the following package specification.

 

package MyPack;

 

In order for a program to find MyPack, one of two things must be true. Either the program is executed from a directory immediately above MyPack, or CLASSPATH must be set to include the path to MyPack. The first alternative is the easiest (and doesn't require a change to CLASSPATH), but the second alternative lets your program find MyPack no matter what directory the program is in. Ultimately, the choice is yours.

 

The easiest way to try the examples shown in this book is to simply create the package directories below your current development directory, put the .class files into the appropriate directories and then execute the programs from the development directory. This is the approach assumed by the examples.

 

A Short Package Example

 

Keeping the preceding discussion in mind, you can try this simple package:

 

// A simple package

package MyPack;

class Balance {

String name;

double bal;

Balance(String n, double b) {

name = n;

bal = b;

}

void show() {

if(bal<0)

System.out.print("--> ");

System.out.println(name + ": $" + bal);

}

}

class AccountBalance {

public static void main(String args[]) {

Balance current[] = new Balance[3];

current[0] = new Balance("K. J. Fielding", 123.23);

current[1] = new Balance("Will Tell", 157.02);

current[2] = new Balance("Tom Jackson", -12.33);

for(int i=0; i<3; i++) current[i].show();

}

}

 

Call this file AccountBalance.java, and put it in a directory called MyPack. Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory.

 

Then try executing the AccountBalance class, using the following command line:

 

java MyPack.AccountBalance

 

Remember, you will need to be in the directory above MyPack when you execute this command, or to have your CLASSPATH environmental variable set appropriately. As explained, AccountBalance is now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot use this command line:

 

java AccountBalance

 

AccountBalance must be qualified with its package name.

No comments: