Java Packages and API
Packages in Java are used to group related classes and interfaces together. They help organize your code and prevent naming conflicts. The Java API (Application Programming Interface) is a collection of prewritten packages, classes, and interfaces with their respective methods, fields, and constructors.
1. Packages
A package is declared at the top of a Java source file using the package
keyword.
package com.example.myapp;
public class MyClass {
// Class code here
}
2. Importing Packages
You can import classes and packages using the import
keyword.
import java.util.List;
import java.util.*; // Imports all classes in java.util package
3. Java API
The Java API is a set of classes and interfaces that come with the JDK. Commonly used packages include:
java.lang
: Fundamental classes (automatically imported).java.util
: Utility classes like collections framework.java.io
: Input and output classes.java.math
: Mathematical functions and big numbers.
4. Example: Using the Java API
import java.util.ArrayList;
public class ApiExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
for (String item : list) {
System.out.println(item);
}
}
}
5. Creating Your Own Packages
You can create your own packages to organize your classes.
// In file MyClass.java
package com.mycompany.myapp;
public class MyClass {
// Class code here
}
// In another file
import com.mycompany.myapp.MyClass;
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
// Use obj
}
}
6. Key Takeaways
- Packages help organize code and avoid naming conflicts.
- The Java API provides a vast library of prewritten classes and interfaces.
- Use the
import
statement to access classes from packages. - Creating your own packages enhances code modularity and reusability.