Packages in Java

There are millions (or more) Java classes containing code. Java library itself has thousands of classes. Consider a case when a programmer writes a class having class name HashMap. Java library itself has HashMap class. If programmer uses HashMap class in code, then the question is which HashMap class to use out of the two. This is an example of naming conflict. Similarily, other programmers may also write class having HashMap as its name.

So to organize classes (or code), Java has packages. You can think of a package as a folder to keep files. If you have worked on Windows, we believe you already know about the folder.

A folder can have files and subfolders. And a subfolder itself can have files and subfolders. Similarily, a package can have classes and subpackages. And a subpackage can again have classes and subpackages.

  • Packages are used to organize code/programs (or classes).
  • Members of packages are top level class types, interface types and subpackages. Each package can have subpackages and classes.
  • Packages help in preventing naming conflict.
  • A top level type is accessible outside the package that declares it if the type is declared ‘public’.
  • It is possible to have an unnamed package.
  • A package can be stored in a database or file system.

Example: java.lang is a package provided by Java library.

Packages use hierarchical naming structure. To refer to a type in a package we use fully qualified name of the type. For example, java.lang.String refers to String class in java.lang package.

com.learnitweb.HashMap and java.util.HashMap refer to different types in two different packages.

Package declaration

Every compilation unit (think of a class or interface) declares to which package it belongs to.

In the following code, class Test belongs to package com.learnitweb.utils

package com.learnitweb.utils

class Test {
	// code not written for the sake of brevity
  • If a compilation unit does not have a package declaration then it is a part of unnamed package.
  • The package name in package declaration should be fully qualified name.
  • A package declaration, if used, must be the first thing in the file.
  • Unnamed packages are provided by Java for convenience to write very small and simple application.
  • An unnamed package can not have a subpackage.

Example of a class which is a part of unnamed package.

public class Test {
	public static void main(String[] args) {
		System.out.println("Hello world");