The perfect place for easy learning...

Java Programming

×

Topics List


Defining Packages in java





In java, a package is a container of classes, interfaces, and sub-packages. We may think of it as a folder in a file directory.

We use the packages to avoid naming conflicts and to organize project-related classes, interfaces, and sub-packages into a bundle.

In java, the packages have divided into two types.

  • Built-in Packages
  • User-defined Packages

Built-in Packages

The built-in packages are the packages from java API. The Java API is a library of pre-defined classes, interfaces, and sub-packages. The built-in packages were included in the JDK.

There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax, swing, net, sql, etc.

We need to import the built-in packages to use them in our program. To import a package, we use the import statement.

User-defined Packages

The user-defined packages are the packages created by the user. User is free to create their own packages.

Definig a Package in java

We use the package keyword to create or define a package in java programming language.

Syntax
package packageName;

🔔 The package statement must be the first statement in the program.

🔔 The package name must be a single word.

🔔 The package name must use Camel case notation.


Let's consider the following code to create a user-defined package myPackage.

Example
package myPackage;

public class DefiningPackage {

	public static void main(String[] args) {

		System.out.println("This class belongs to myPackage.");

	}

}

Now, save the above code in a file DefiningPackage.java, and compile it using the following command.

javac -d . DefiningPackage.java


The above command creates a directory with the package name myPackage, and the DefiningPackage.class is saved into it.

Run the program use the following command.

java myPackage.DefiningPackage


🔔 When we use IDE like Eclipse, Netbeans, etc. the package structure is created automatically.