Setting Java CLASSPATH and using Packages

3 Comments

I have a very little experience on java and this blog is meant to be my future personal reference. so if you are still reading this blog for a in-depth concept on these topics; better you look elsewhere.

Ok, till now it was totally clumsy to me that what the heck is CLASSPATH and what is the relationship between CLASSPATH and packages. Now I guess I have a little understanding on it.

CLASSPATH: Java CLASSPATH is the PATH or location or directory where java run-time system looks for CLASSES or PACKAGES, where classes are located.

Packages: Packages may be compared to folders where different class files are located. To indicate that a class file belongs to that package we need to write the following statement at the beginning of that file:

package pkg;

To import a package we need to write:

import pkg1.pkg2.classname;

Example
Now let’s see an example. Open the command prompt and set the CLASSPATH to

C:>set CLASSPATH=.;C:;

by this statement we are telling the JRE to look for clases in the C: directory and its subdirectory. Now create two files in following directories:

1.C:onePackOne.java
2.C:twoPackTwo.java

****Code for One.java****

<strong>package onePack;
import twoPack.Two;</strong>
class One{
public static void main(String args[])
{
Two two = new Two(2);
two.show();
}
}

****Code for Two.java****

<strong>package twoPack;</strong>
public class Two{
private int b;
public Two(int a)
{
b = a + 10;
}
public void show()
{
System.out.println(b);
}
}

These two statements binds each class to the specified Package:

package onePack;
package twoPack;

Also note the use of import. It tells One to use the Two class file from twoPack package. Here CLASSPATH plays the role to where from start searching for classes.

After compiling the source files type the following code:

C:&gt;java onePack.One

This is needed to do so because now One belong to package onePack and this is its fully-qualified class name.

CHANGING THE CLASSPATH:

By changing the CLASSPATH we can put our packages in any directory and import them as we like.

Let us put twoPack folder in D: directory. Now we need to change our CLASSPATH as

C:&gt;set CLASSPATH=.;C:;D:;

Recompile One to let it know the new location of Two.class file. Now type the command:

C:&gt;java onePack.one

Hope it runs successfully. Hence we imported our needed class twoPack.Two from a different directory and used it.

3 Responses to “Setting Java CLASSPATH and using Packages”

  1. abel

    good job. helpful. thanks….

    Reply
  2. infostall

    nice info in the simplest way.keep simplifying.

    Reply
  3. Joe B

    Great code sample outlining the relationship between CLASSPATH and package. While both topics, CLASSPATH and package, are covered in textbooks your site taught me why it is essential to understand CLASSPATH’s effect on package and overall design.

    Reply

Leave a Reply