Understanding Packages and classpath in Java


What is Package?

Package in Java is a way of organizing the code. In simple terms, its an directory or directory hierarchy which is used to store the code files. A statement like import java.util.Scanner means that on system java is a directory which in turns have sub directory name util, which have Scanner class. To create custom package the procedure is to create a directory and sub directories and declare it java file. Consider a class A, which belongs to a package org.demo, save it as A.java.

Code - Class A

Code – Class A

The first statement is used to say that class A belongs to package org.demo, package is a keyword used to denote the path of package. To create the directory structure and store the compile file use -d flag with javac command. Compile the java file using

javac -d . A.java

-d .  : Instructs the compiler to create the required directory structure in current directory and store the A.class in directory. After this command following directory structure will be created in current directory.

package

 

To use the class A simply add import org.demo.*; in program, as shown below

Code using package

Code using package

Compile and execute the Test.java which will give us a result.

Understanding CLASSPATH

In above case the Test.java and org folder belongs to same path. So there is no need to tell java where the org directory is as it will look in to the current directory to which Test.java belongs.

In case say org directory and Test.java does not belong to same directory, classpath is used to specify where to find the org directory. Now to compile the Test.java program

javac -cp c:\javademo\packagesdemo Test.java

-cp is used to specify the classpath for Test.java code. Now org directory will be looked in to c:\javademo\packagesdemo directory, in simple words import org.demo.* will means look in c:\javademo\packagesdemo\org\demo.

 

Leave a comment

Your email address will not be published. Required fields are marked *