What is package and what is the advantage?

What is package and what is the advantage?

Package

What is package and what is the advantage?

It is an encapsulation mechanism to group related classes and interface into a single unit, which is nothing but packages. Packages are named in reverse order of domain names, i.e., com.java4us.packageprogram.A Java package is a group of similar types of classes, interfaces, and sub-packages. There are many built-in packages such as Java.lang, awt, javax, swing, net, io, util, sql etc. Java uses file system directories to store packages. For example all .java file for any class you define to be part of java4us package must be stored in a directory called java4us.

Example 1– All classes and interface which are required to DB operations are grouped into a single package which is nothing but a java.sql package

Example 2 — All classes and interface which are used for file input-output operations or grouped into a separate package which is nothing but the java.io package.

The main advantages of packages are:-

  • To resolve naming conflux( ie unique identification of our components)
  • Java package provides access protection.
  • It improves modularity of the application.
  • It improves maintainability of the application.
  • It provides security for our components.
//What is package and what are the advantage?

package java4us;  
public class Test{  
 public static void main(String args[]){  
    System.out.println("Welcome to Java4us.com");  
   }  
}  
To compile: javac -d . Test.java
To run:  java java4us.Test
What is package and what is the advantage?

Conclusion

  • In any java source file there can be at most one package statement ie more than one package is not allowed otherwise we will get compile time error: class, interface, or enum expected.
  • In any java program the first non-comment statement should be package statement (If it is available) otherwise we will get compile time error.
  • The following is the valid java source file structure.
  • Package statement (at most one )
    Import statement (any number)
    Class/interface/enum declaration (any number)

Leave a Reply

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

*