A Package is a collection of predefined classes and interfaces. Using packages, classes can be partitioned into smaller units on the basis of their functionality. Basically, packages in Java are folders or directories in file system, containing class files and sub directories. For example, the most important package in Java API is java.lang because without it, a Java program cannot be developed. Here, java is a package and lang is its sub package. It consists of commonly used classes i.e. Object, String, Math, Class, Thread, Exception, Runnable, RuntimeException, etc. and various wrapper classes like Integer, Double, Float, Character, etc.
A Java package can have two types of members:
  • Compilation Units
  • Sub-Package
  • A compilation unit is a source code file of Java (also known as translation unit). Each compilation unit must have a name, ending with .java extension. A compilation unit can have a public class that must have same name as the fi le name. Only one class can be declared public in a compilation unit, otherwise the complier will show error message.
    If a compilation unit contains additional non-public classes, they will be hidden from the outside world but can be used as support classes to the main public class.
  • A sub-package is a subdirectory or a sub-folder that may also contain compilation unit and sub-package of its own.

Named and Unnamed Packages

Named Packages

A package declaration in a compilation unit specifies the name of the package to which the compilation unit belongs.
Package declaration syntax:
         package packageName;

Unnamed Packages

A compilation unit without package declaration part belongs to unnamed package. Unnamed package is also known as default package or anonymous package. Most of the examples in this site use single file without package declaration, it means, these example programs belongs to unnamed package.
For Example:
  class demo
    { public static void main(String args[])
        { System.output.println(“Learn Java Really”);

Creating Package

We are going to create a package. The structure of the package to be created, is shown below:
Steps for creating and using package:
  1. Create folder(package) "realjava" having 2 sub folders(sub-packages) "loops" and "decisions" in "jdk/bin" folder.
  2. Create "" and "" files and save them "realjava\loops" package. The code of both files is given below:
  3. : for sum of n natural numbers.
      package realjava.loops;
      public class SumN //Class must be public 
          public void doSum(int n)//method must be bublic
              int i=1,sum=0;
        } : for factorial of n.
      package realjava.loops;
      public class FactN //Class must be public 
          public void factorial(int n)//method must be public
              int i=1,fact=1;
  4. Similarly create "" and "" files and save them in "realjava\decision" package. The code of both files is given below:
  5. : for greater of 2 numbers.
      package realjava.decision;
      public class Max2 //Class must be public 
          public void max2(int a,int b)//method must be bublic
            	System.output.println(“A is Greater" );
              	System.output.println(“B is Greater" );
        } : for greatest of 3 numbers.
      package realjava.decision;
      public class Max3 //Class must be public 
          public void max3(int a,int b,int c)//method must be bublic
              if(a>b && a>c)
            	System.output.println(“A is Greatest" );
              	System.output.println(“B is Greatest" );
                   System.output.println(“C is Greatest" );
  6. Using package:Create "" file and save it in "jdk\bin" folder. For using the ".java" file from "realjava" package we use the import declarations as shown in program below:
        import realjava.loops.*; //to import all files
        import realjava.decision.Max2;  //to import file only
        class UsePack
          public static vooid main(String args[])
              SumN s=new SumN();
              FactN f=new FactN();
              Max2 m2=new Max2();
            //using fully qualified path to use
              realajava.decision.Max3 m3=new realajava.decision.Max3();
    Compile and interprete the program( to see the expected output.

Using/Accessing Packages

Packages in Java can be accessed using:
  1. Import declarations
  2. Fully qualified name
  1. Import declarations
  2. Import declaration statement(if any) must be the first statement after package declaration statement in your program.
    Import Declaration Types:
    1. Single-Type-Import Declaration.
    2. Type-Import-On-Demand Declaration.
    3. Single-Static-Import-Declaration.
    4. Static-Import-On-Demand-Declaration.
    1. Single-Type-Import Declaration
    2. It imports a single type (class, interface) by specifying its canonical name. Some times fully qualified name is used as an alternative of canonical name. The difference between both can be seen in the following example:
             package p;
             class A { class AA { }
             class B extends A { }
      In this example p.A.AA and p.B.AA are fully qualified names but only p.A.AA is canonical name.
      Syntax : Single-Type-Import Declaration:
      import TypeName;
      Note that, TypeName must be the canonical name of a class or an interface and it must be in existence, for example:
      import java.util.ArrayList;
      The above statement avails class ArrayList only from java.util package in the compilation unit.
      If there are two import declarations to import a class or an interface with same name, then the compiler shows error message. Consider the following lines of code:
      import packa.Rect;
      import packb.Rect;
      This causes compile time error because of duplicate declarations of Rect type. If the type (class or interface) imported is also declared in the same compilation unit, then the import type is ignored, as shown below:
      import packa.Rect
      class Rect {
    3. Type-Import-On-Demand Declarations
    4. A type-import-on-demand declaration avails all the types (classes, interfaces) to the compilation unit.
             import PackageName.*;
      The package name must be the canonical name of the package for example:
      The above statement will avail all the public types to the compilation unit for use.
      Each compilation unit automatically imports all the public types declared in the predefined package java.lang.
      If there are two packages first:packa containing a class Rect and other:packb also containing a class Rect, then use the following import declarations:
      import packa.*;
      import packb.Rect;
      The above statements will not cause compile-time error because class Rect of packb will have higher priority while instantiation.If you write the following declaration statements:
      import packa.*;
      import packb.*;
      This will cause ambiguity error on instantiation of class Rect in compilation unit code. To resolve ambiguity, full qualifi ed path can be used as follows:
      packa.Rect ref = new packa.Rect ();
    5. Single-Static-Import Declarations
    6. Using import statement to access the static members of a type (class,interface) from packages is often called static import.Using a single static import declaration, you can avail only one static member(field, method, class,interface).It means that for multiple static members, you will need multiple single-static-import declarations.
      Syntax: import static PackageName.TypeName.staticMemberName;
    7. Static-Import-On-Demand Declarations
    8. It avails all static members of a type to the compilation unit.
      Syntax:  import static packageName.typeName.*;
  3. Fully Qualified Name
  4. Types (classes, interfaces) from packages can be accessed without using import declarations also. It is possible using fully qualifi ed name.
    Syntax:   packageName.TypeName refVar=new packageName.TypeName();
    But using fully qualified name in code for use types is not a very good programming practice.

    Accessibility Specifiers

    Using accessibility specifiers provided in Java, a class can control the visibility of its members to the outside world.
    Types of accessibility Specifiers:
    1. public
    2. protected
    3. default (package accessibility)
    4. private
    1. public Members
    2. The public members of a class are accessible everywhere, whether it is in the same package or in other packages. These are accessible in derived and non-derived classes whether of the same package or in other packages, as shown below:
      real java  packages public
    3. protected Members
    4. Members declared using keyword protected are accessible in all classes in the same package, whether the classes are derived or non-derived. But for other packages, these are accessible in derived classes only. However, non-derived classes of other packages can not access them, as shown follows:
      real java  packages proteched
    5. Default/Package Accessibility Members
    6. Members of a class, declared without any accessibility specifi er, have default accessibility. They are accessible in derived and non-derived classes of same package only. Even if the class is public, these members are not visible in other packages, as shown below:
      real java  packages default
    7. private Members
    8. The private members of a class have more restrictive access as compared to other accessibility specifi ers. It is because private members are accessible within the owning class only and other classes can not access them. Even, private members are not accessible in the derived classes of the same package. Unlike C++,members declared without any accessibility specifi er are not private, instead they have default accessibility, as shown below:
      real java  packages private
About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
17 Years experience in Training & Development. Founder of, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android. If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on
#Email : [email protected] #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "". M:9872246056
Card image cap