Java Packages
A package is a namespace that groups related classes and interfaces, helping organize large codebases and avoid naming conflicts. Package names typically follow a reversed domain convention, like com.example.myapp.
You use `package` at the top of a file to declare its package, and `import` to use classes from other packages.
package com.example.myapp;
import java.util.ArrayList;Declaring and importing packages
The `package` statement must be the first line in a Java file (aside from comments). `import` statements bring in classes from other packages so you can use their simple names.
Built-in packages
java.lang is imported automatically. java.util provides collections, java.io provides file/stream handling, and many more standard packages exist.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Java");
System.out.println(list);
}
}[Java]ArrayList is imported from java.util and used to store and print a list.
Key points
- Packages organize related classes and avoid naming conflicts.
- package must be the first statement in a file.
- import brings in classes from other packages.
- java.lang is imported automatically into every file.
