Packages in Java

by anupmaurya
0 comment

In this article, you’ll learn about Packages in Java, Advantages of Packages , Types of Packages, Creating a Package and The “import” keyword .

  • A package is a mechanism to group the similar type of classes, interfaces and sub-packages and provide access control.  
  • It organizes classes into single unit.
  • In Java already many predefined packages are available, used while programming.

For example: java.lang,, java.util etc.

Advantages of Packages

  • Packages provide code reusability, because a package has group of classes.
  • It helps in resolving naming collision when multiple packages have classes with the same name.
  • Package also provides the hiding of class facility. Thus other programs cannot use the classes from hidden package.
  • Access limitation can be applied with the help of packages.
  • One package can be defined in another package.

Types of Packages

There are two types of packages available in Java.

1. Built-in packages
Built-in packages are already defined in java API. For example: java.util,, java,lang, java.awt, java.applet,, etc.
2. User defined packages
The package we create according to our need is called user defined package.

Creating a Package

We can create our own package by creating our own classes and interfaces together. The package statement should be declared at the beginning of the program.

package <packagename>;
class ClassName

Example: Creating a Package

package p1;
class Demo
   public void m1()
       System.out.println("Method m1..");

How to compile?

Syntax:  javac –d directory javafilename
For Example: javac –d .

How to run?

To run: java p1.Demo

Example: Program to create and use a user defined ackage in Java.

// package vehicles; interface Vehicle { public void run(); public void speed(); } // package vehicles; public class Bike implements Vehicle { public void run() { System.out.println("Bike is running."); } public void speed() { System.out.println("Speed of Bike: 50 Km/h"); } public static void main(String args[]) { Bike bike = new Bike();; bike.speed(); } }
Code language: PHP (php)


javac –d .
javac –d .


java vehicles.Bike


Bike is running
Speed of Bike: 50 Km/h

The “import” keyword

  • The import keyword provides the access to other package classes and interfaces in current packages.
  • “import” keyword is used to import built-in and user defined packages in java program.

There are different 3 ways to access a package from other packages.

1. Using full qualified name


class Demo extends java.util.Scanner

2. import only single class


import java.util.Scanner;
class Demo
      // statements

3. import all classes


import java.util.*;
class Demo
    // statements

You may also like