Java Packages and Imports
A package is a folder of related classes. Packages keep big projects organized and avoid name clashes: two different classes can both be named Date if they are in different packages.
Built in packages
| Package | Contains |
|---|---|
| java.lang | Core classes (String, Math, System). Imported automatically |
| java.util | Collections, Scanner, Random |
| java.io, java.nio.file | Files and streams |
| java.time | Dates and times |
| java.net | Networking |
import
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Riya");
System.out.println(names);
System.out.println(LocalDate.of(2026, 1, 15));
}
}
[Riya]
2026-01-15
import java.util.*; imports all the classes of a package. It is fine, but many teams prefer to import each class, so it is clear where a name comes from.
Create your own package
The package statement must be the first line, and the folders must have the same name. We make a small project with two files:
package com.shop;
public class Product {
private final String name;
private final double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String describe() {
return name + " costs " + price;
}
}
import com.shop.Product;
public class Main {
public static void main(String[] args) {
Product p = new Product("Book", 250);
System.out.println(p.describe());
}
}
$ find . -name "*.java"
./com/shop/Product.java
./Main.java
$ javac -d out com/shop/Product.java Main.java
$ java -cp out Main
Book costs 250.0
$ find out -name "*.class"
out/com/shop/Product.class
out/Main.class
javac -d out puts the compiled classes in the out folder, with the package folders. -cp out tells Java where to look for the classes (the class path).
Static import
import static java.lang.Math.*;
public class Static {
public static void main(String[] args) {
System.out.println(sqrt(144) + " " + max(3, 8) + " " + PI);
}
}
12.0 8 3.141592653589793
Name clash
When two classes have the same name, use the full name:
public class Clash {
public static void main(String[] args) {
java.util.Date a = new java.util.Date(0);
java.sql.Date b = new java.sql.Date(0);
System.out.println(a.getClass().getName());
System.out.println(b.getClass().getName());
}
}
java.util.Date
java.sql.Date
Naming convention
Package names are in small letters, and start with a reversed domain name: com.tutorialsclass.shop. This makes them unique in the world.
Modules (short note)
Since Java 9 there is also the module system (module-info.java) for very big applications. Most beginners and many projects do not need it.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |