Java packages

Packages are containers for classes. Packages are collection of similar type of classes in Java. In java there are two types of packages - User Defined Package and Built in Packages.

A. Need of Packaging :

  1. Maintainability : Suppose we are developing the big project then instead of keeping all the classes together under same name we can categorize them in the different folders called package.
  2. Avoid Confusion : If Java provides us complete code in single package then it would be very difficult to get required api. In order to make everything clear, Java provides us everything in the package so that we can import only those packages that are required in the application.
  3. Avoid naming conflicts
  4. Control access

B. How to Import classes and packages :

When we are using the import statement as first statement then we are importing the required classes that are being used in current application.

Import All the Classes of Package :

import java.util.*;
  • In the above statement, we are importing all the classes of the package util.
  • An import statement can import all the classes in a package by using an asterisk wildcard

Import Single Class of Package :

import java.util.ArrayList;

In the above statement we are just importing the ArrayList class of the util package. Due to this facility to import the specific class in the application, we can avoid necessary importing of classes in the application.