A package is a namespace that organizes a set of related classes and interfaces.

Package is a collection of classes, interfaces, multiple sub packages etc.

Some of the existing packages in Java are:

·        java.lang - bundles the fundamental classes

·        java.io - classes for input , output functions are bundled in this package

Advantages of packages -:

·   Reusability:  Reusability of code is one of the most important requirements in the software industry. Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any number of programs wishing to incorporate the class in that particular program.

·      Easy to locate the files.

·    In real life situation there may arise scenarios where we need to define files of the same name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-space collisions”.

Types of package:

1.      User defined package: The package we create is called user-defined package.

2.      Built-in package: The already defined package like java.io.*, java.lang.* etc are
known as built-in packages

// define package
package packagename;
// import packages
Import mypack;
//class declaration
class Sample
// instance members
//method implementation





Define a package

package  <package name>;

Example of package of creation

package mypack;

class Book


 String bookname;

 String author;

 Book(String b, String c)


  this.bookname = b;

  this.author = c;


 public void show()


  System.out.println(bookname+" "+ author);




class test


 public static void main(String[] args)


  Book bk = new Book("java","Herbert");





Access of package-:


import java.util.Date;

Subpackage in java-:

Package inside the package is called the subpackage. It should be created to categorize the package further.

Example of sub packages

package com.midstick.core;  
class Sample{ 
  public static void main(String args[]){ 
   System.out.println("Demo subpackage"); 

package com.mindstick.core
import static java.lang.Math.*;
public class Test
    public static void main(String[] args)

output -: 12  


  Modified On Dec-06-2017 07:45:34 AM

Leave Comment