The package to which the source file belongs is specified with the keyword
package at the top left of the source file, before the code that
defines the real classes in the package.
Suppose we have a source file called "HelloWorld.java" and we
want to put this file in a package "mypackage" then the
following code is written as shown in the given example:
package mypackage;
|
Before running this program make sure to do the following things:
| C:\mypackage>javac HelloWorld.java |
If you try to run this program, you will get the following exceptions (or error):
| C:\mypackage>java HelloWorld Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name: mypackage/HelloWorld) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) |
This is, because the class "HelloWorld"
belongs to the package "mypackage". So If we want to run it, we
have to tell the JVM about its fully-qualified class name as (mypackage.HelloWorld)
instead of its plain class name (HelloWorld). Fully-qualified class name
is the name of the java class that includes its package name.
Now run the program as shown:
C:\mypackage>java mypackage.HelloWorld
Hello World!
The ways to Compile the Package:
Compile in the same directory: If you have a hierarchy of packages to compilation then you can compile the package without going to the subdirectories and specifying the complete directory path with the class . Suppose, you have a hierarchy of packages as "india.mycompany.mainpackage.mypackage" including the class "HelloWorld" then type the following command shown as:
| C:\javac C:\india\mycompany\mainpackage\mypackage\HelloWord.java
|
This command will reach to the last subdirectory and compile the class "HelloWorld".
Compile into the Different Directory: On the other hand, if you want to compile the same package available in the hierarchy manner to another directory (location) then syntax is shown as:
| C:\javac -d <target_directory> <complete_directorypath> |
Suppose, you want to save the compiled package to the location "D:\myfolder" then type the following command shown as:
| C:\javac -d D:\myfolder
C:\ india\mycompany\mainpackage\mypackage\HelloWord.java
|
This command puts the folder "india" along with its subfolders and the class file "HelloWorld.class" to the new location as D:\myfolder.
 
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Create Your Own Package View All Comments
Post your Comment