In Java package is defined as the logical container which can contain logically related classes, interfaces and sub packages.

Purpose of package in java -

Concept of package is used to uniquely differentiate the classes of same name in same directory. It it is used to remove the naming confliction between the classes of same name

In software development there may be several classes having same name in same project. Hence to differentiate one class from another class some mechanism is required , packages are used for this purpose.

Type of package in java

1) Pre defined Packages or built in packages
2) User defined packages.

  • Predefined or built-in package

    Predefined packages are those which are developed by SUN micro systems (Oracle) and supplied as a part of JDK (Java Development Kit) to simplify the task of java programmer. There are many predefined packages in java some of them are as follows: -

    Predefined or built-in package
    • java.lang.* - This package is used for achieving the language functionalities such as conversion of data from string to fundamental data, displaying the result on to the console, obtaining the garbage collector. This package is by default imported for each and every java program.

    • java.io. * - This package is used for developing file handling applications, such as, opening the file in read or write mode, reading or writing the data, etc

    • java.util. * - This package contains utility based classes such as Scanner class, Date Class, Collection Framework API etc.
      Collection framework is the standardized mechanism of grouping of similar or different type of objects into single object. This single object is known as collection object.

    • java.net. * - This package contains all the class related to Java networking. This package is used for developing client server applications.

    • java.text. * - This package is used for formatting date and time on day to day business operations.

    • java.sql. * - This package is used for retrieving the data from database and performing various operations on database.

    • many more ..


    Example of predefined package.

    //example of using Date class of java.util package
    class Example {
    	public static void main(String arr[]) {
    		// create the object of Date class
    		// in order to use Date class we have to use package with class
    		java.util.Date d = new java.util.Date();
    		String str = d.toString();
    		System.out.println(str);
    
    	}
    }

    Output:
    Mon Dec 25 17:30:01 IST 2017
  • User defined package

    A user defined package is one which is developed by java programmers to simplify the task of the java programmers to keep set of classes, interfaces and sub packages which are commonly used. Any class or interface is commonly used by many java programmers that class or interface must be placed in packages.

    ' package ' keyword used to define any java package.

    Syntax to declare package:

    package [packageName].[subPackageName].[subPackageName] ;

    RULE : Whenever we create user defined package. package statement must be the first line of java source code.

  • How to create package in java :

    Steps-

    • Choose the appropriate package name, the package name must be a JAVA valid variable name and we should ensure the package statement must be first executable statement in source code.

    • Choose the appropriate class name or interface name and whose modifier must be public .

    • The modifier of Constructors of a class must be public.

    • The modifier of the methods of class name or interface name must be public.

    • Save the file with same name as class Name. for example: FileName.java.
      FileName=ClassName

    Note : we have used public as modifier so that our class can be accessed from outside of the package.


    Simple example of Java package.

    package mypack;
    public class Simple {
    	public Simple() {
    		System.out.println("This is a Constructor");
    	}
    
    	public void sayHello() {
    		System.out.println("Hello , I am very simple boy...");
    	}
    }


    How to Compile :

    javac -d path fileName.java
    //path- path where we want create package folder.
    //for above example 
    java -d . Simple.java

    In above syntax "-d" is a specific tool which is tell to java compiler create a separate folder for the given package in given path. When we give specific path then it create a new folder at that location and when we use . (dot) then it crate a folder at current working directory.


    How to execute :

    java fullyQualifiedName 
    //fullyQualifiedName- packageName.className
    //for above example 
    java mypack.Simple

    Above program does not contain main() method so we get run time error.


    Now create another class and used above(Simple class) in this class.

    class Example
    {
    public static void main(String arr[])
    {
       mypack.Simple s=new mypack.Simple(); //use  Simple with package name
        s.sayHello();
    }
    }

    Output:
    This is a Constructor
    Hello , I am very simple boy...

    Compile and Execute this program normally.
    javac Example.java
    java Example

  • How to use the Class present in the package

    There are 3 ways to access any class present in package.

    • By using fully qualified name of the class. For example packageName.ClassName .

    • By importing all the classes of the package . for example import packageName.*

    • By importing the single class of the package . for example import packageName.ClassName

  • 1) using class with fully qualified name in java.

    Fully qualified name means class name with package name.
    for example java.lang.String

    It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.


    Example : create Sum class inside package p1.p2.p3

    //save the file - Sum.java
    package p1.p2.p3;//package declaration
    public class Sum
    {
    int a,b;
    public Sum(int x,int y)
    {
     a=x;
     b=y;
    }
    public void printSum()
    {
    System.out.println("Sum ="+(a+b));
    }
    }

    compile using : javac -d . Sum.java


    now create another class and use the above class in this class.

    package p1.p2.p3;//declaring package
    public class Example
    {
    public static void main(String arr[])
    {
    //now use Sum class here using fully qualified name.
        p1.p2.p3.Sum ob=new p1.p2.p3.Sum(34,43);
        /*
        p1.p2.p3.Sum - is fully qualified name of Sum.
        
        
        p1-package
        p2-sub package
        p2-sub package
        
        */
        ob.printSum();
    }
    }

    Output:
    Sum =77

    compile using : javac -d . Example.java
    run using : java p1.p2.p3.Example

  • 2) accessing class using packageName.*

    import packageName.* is used to import all the classes of another package to the current program , so that we can use the classes in current program.

    The import keyword is used to make classes and interfaces available and accessible to the current source code, without specifying fully qualified package names.


    Example : create Sum class in package p1.p2.p3

    //save the file - Sum.java
    package p1.p2.p3;//package declaration
    public class Sum
    {
    int a,b;
    public Sum(int x,int y)
    {
     a=x;
     b=y;
    }
    public void printSum()
    {
    System.out.println("Sum ="+(a+b));
    }
    }

    compile using : javac -d . Sum.java


    Now create another class and use above class.

    package p1.p2.p3;//declaring package
    import p1.p2.p3.*;//import all the classes of p1.p2.p3 package.
    public class Example
    {
    public static void main(String arr[])
    {
    //now use Sum class here 
       Sum ob=new Sum(22,44);
        /*we can directly use Sum class in this program 
        because we have imported all the classes of p1.p2.p3
        and Sum is one of them.
        */    
        ob.printSum();
    }
    }

    Output:
    Sum =66

    compile using : javac -d . Example.java
    run using : java p1.p2.p3.Eample

  • 3) accessing class using packageName.ClassName

    import packageName.ClassName is used to import the single class in the current program . so that we can use that single class in this program.


    Example: Create the class with name Sum in package p1.p2.p3

    //save the file - Sum.java
    package p1.p2.p3;//package declaration
    public class Sum
    {
    int a,b;
    public Sum(int x,int y)
    {
     a=x;
     b=y;
    }
    public void printSum()
    {
    System.out.println("Sum ="+(a+b));
    }
    }

    compile using : javac -d . Sum.java


    Now create class with main() method .

    package p1.p2.p3;//declaring package
    import p1.p2.p3.Sum;//importing only Sum class in this program.
    public class Example
    {
    public static void main(String arr[])
    {
    //now use Sum class here 
       Sum ob=new Sum(220,44);
         
        ob.printSum();
    }
    }

    Output:
    Sum =264

    compile using : javac -d . Example.java
    run using : java p1.p2.p3.Example

Note

If you import a package, subpackages will not be imported.

Concept of package is only applied on class files not on java files.

Note

The standard of defining package is domain.company.package e.g. com.onlyjavatech.dao

What next?

The next topic is classpath concept in java

Share this page