Java Packages & API
In Java, a package is a namespace that groups related classes and interfaces together.
Conceptually, it works like a folder in a file system: it organizes code, prevents naming conflicts,
and improves maintainability in large applications.
Packages in Java fall into two main categories:
- Built-in packages — provided by the Java standard library (Java API)
- User-defined packages — created by developers to organize their own code
What Is the Java API?
The Java API (Application Programming Interface) is a vast collection of prewritten classes and interfaces included with the Java Development Kit (JDK). It provides ready-to-use functionality for:
- Input and output operations
- Data structures and collections
- Networking
- Date and time handling
- Database connectivity
- Utility operations
The official documentation is maintained by Oracle and available at:
https://docs.oracle.com/javase/8/docs/api/
The API is organized into packages, and each package contains multiple related classes.
Importing Packages and Classes in Java
To use classes from another package, Java provides the import keyword.
Import syntax
import packageName.ClassName; // Import a single class
import packageName.*; // Import all classes in a package
Importing a Single Class — Example
The Scanner class (from java.util) allows programs to read user input from the console
Example: Reading user input with Scanner
import java.util.Scanner;
public class UserProfileApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.print("Enter your age: ");
int age = input.nextInt();
System.out.println("Welcome " + name + "! You are " + age + " years old.");
input.close();
}
}
Explanation
- java.util → package
- Scanner → class
- nextLine() and nextInt() → methods of the Scanner class
Importing an Entire Package
Instead of importing classes individually, you can import all classes from a package using *.
import java.util.*;
This makes all classes from java.util available, such as:
- Scanner
- Random
- ArrayList
- Date
Best practice: Import only the classes you need to avoid unnecessary namespace pollution and improve readability.
Creating User-Defined Packages in Java
Step 1: Define the package
Example: Creating a utility package
File: MathUtility.java
Step 2: Compile the package
Step 3: Use the user-defined package
Compile and run:
Output
Package Naming Conventions (Best Practices)
- Use lowercase letters
- Use reversed domain names for uniqueness
- Avoid spaces and special characters