Package in java is nothing but a kind of directory which contains a group of similar types of classes, interfaces and subpackages. Packages can be created by right click on the src folder and select option package and give it a name.


You need to use the keyword package in the program to access the components in that package.Packages can be categorized in 2 categories.

  • In-built packages
  • user defined packages

In-built packages are like java, lang, awt, javax, swing, util, sql, io ,net etc.

User defined packages can be like any desired name which suits the requirement.In our example ,we have create a packages called com.testingpol.demo.(as shown below)

Advantages of packages:

  • Packages can be used to maintain the similar kind of classes in one directory.
  • Remove naming collision.
  • Provides access protection.

Subpackages : It will be created inside a package to further clarify it. In our example, we have full package name com.testingpool.demo. In that, testingpool and demo are the subpackages of com.

The standard for defining a package is e.g. com.testingpool.demo

The import keyword is used to access the package from outside. For showing this example, we have created 2 packages com.testingpool.demo and com.testingpool.demo2. A class AddNum is created under the package com.testingpool.demo  and another class SubNumber is created under another pacage com.testingpool.demo2.

Now, if we want to create object of class AddNumber in the second package com.testingpool.demo2.We have to import the first package inside the second package.Look at the below example for better understanding.

Class AddNumber under the package com.testingpool.demo.

Class SubNumber under the package com.testingpool.demo2.

There are 3 ways to access the package into another class or package.

  • By packagename.*
  • By package.classname
  • By using fully package name

Using package.*:

Using Package.classname:

AddNumber is the class under the package com.testinpool.demo.

using full package name:

Instead of importing the package, use the full package name to use its components as shown below.





Methods and return value
Static keyword
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

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