by BehindJava

What are packages in Java

Home » java » What are packages in Java

In this tutorial, we are going to learn about packages and its uses in detail.

What is a Package

  • A package is a namespace that organizes a set of related classes and interfaces.
  • A Java package is a mechanism for organizing Java classes into namespaces.
  • A package is a logical container of classes, interfaces and sub-packages.

Reason to use packages

  • Grouping related classes.
  • In large programs prevents name conflicts.
  • Allows effective use of default “package” visibility.

Defining a Package

  • Each file may have a package declaration which precedes all non-comment code.
  • The package name must be the same as the enclosing directory.
  • Default package: If a package declaration is omitted, all classes in that directory are said to belong to the “default” package.
  • package Package_Name; must be the first statement in a class or interface definition.


	package P1;
	public class Test
		public static void main(String arr[])
				System.out.println(This is package P1”);
  • Compilation: \Package \P1> javac
  • Execution: \Package> java P1.Test

Note: To execute the class file of a package, we need to go back to the parent folder of package and refer the class as- packagename.classname

  • We can create the package while compiling the program.
    javac –d .

Importing a Package

  • ‘import’ keyword is used to import the classes of one package into another package.

    import package_name.*;

  • A class must be publicly defined in the package in order to be imported in other package.
  • Once a class is imported in any package, it can be referenced without package name.
  • If a class is imported but not referenced in importing class, then it will not be loaded (i.e. the imported class will be loaded only when it is referenced ).

Core Packages in Java

  • java.lang : basic language functionality and fundamental types.
  • java.util : collection data structure classes.
  • : file operations.
  • java.math : multiprecision arithmetics.
  • java.nio : the New I/O framework for Java.
  • : networking operations, sockets.
  • : key generation, encryption and decryption.
  • java.sql : Java Database Connectivity (JDBC) to access databases.
  • java.awt : basic hierarchy of packages for native GUI components.
  • javax.swing : hierarchy of packages for platform-independent rich GUI components.
  • java.applet : classes for creating an applet

Note: The java.lang package is available without the use of an import statement.