Package in Java

Package in Java

The package is an encapsulation mechanism to group related classes and interfaces.

Example of package in Java –

  • All classes and interfaces which are required for file input /output are grouped into a seprate package java.io.
  • All classes and interfaces required for Data Base operations are grouped into a single package which is the java.sql package.

Package rules in Java

  • In any Java source file, there can be at most one package statement if there is more than one package statements in the Java source file then we will get compile time error – “java: class, interface, enum, or record expected”.
package thecodedata.com;
package thecodedata;
public class PackageInJava {
    public static void main(String[] args) {
        System.out.println("The Code Data");
    }
}
Package in Jav

  • In any Java program, the first non-comment statement should be a package statement (If it is available) otherwise we will get compile time error – “java: class, interface, enum, or record expected”.
import java.util.*;
package thecodedata.com;
public class PackageInJava {
    public static void main(String[] args) {
        System.out.println("The Code Data");
    }
}
Package in Java

Advantage of package in Java

  • Unique identification of our component (resolve naming conflict).
  • It improves modularity.
  • It imporoves maintainabilty of the code.

Similar Java Tutorials

Leave a Comment