Packages in Java: Definition, Types, and Examples

Package in Java


A package in Java is a collection of related classes, interfaces, and abstract classes that are grouped together as part of an application. Packages help in organizing code, avoiding name conflicts, and improving maintainability.

Types of Packages

Packages in Java are classified into two types:
1. Inbuilt Packages
2. User-Defined (Programmer-Defined) Packages

1. Inbuilt Packages

Inbuilt packages are predefined packages that are available in the JDK software.
These packages usually start with the java keyword.

Examples of Inbuilt Packages

  • java.lang
  • java.sql
  • java.io
  • java.util
  • java.net
  • java.time 
📌 Note: The java.lang package is imported automatically by the JVM.

2. User-Defined (Programmer-Defined) Packages

User-defined packages are created by programmers according to the application requirements.

Package Naming Convention

com.companyname.applicationname.modulename
org.companyname.applicationname.modulename

Example

package com.example.billing.invoice;

Importing a Package

To use classes from another package, the import statement is used.
import packageName.ClassName;
import packageName.*;

Example

import java.util.Scanner;

Creating a Package in Eclipse

1. Open Eclipse
2. Go to File → New → Package
3. Enter the package name
4. Click Finish

Creating a Class in Eclipse

1. Open Eclipse
2. Go to File → New → Class
3. Enter the class name
4. Select the package
5. Click Finish

Advantages of Packages

  • Organizes large projects efficiently
  • Avoids class name conflicts
  • Improves code reusability
  • Supports access protection

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know