Import Package in Java: The import Statement Explained

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 226 of 306

To import a package in Java, you write an import statement at the top of a source file so you can use a class by its short name, such as ArrayList, instead of its full name, java.util.ArrayList. Imports keep code short and readable when you use classes from the JDK, from libraries, or from your own packages.

In this lesson you will learn every form of the import statement: single-type imports, wildcard (on-demand) imports, static imports and the module imports added in Java 25. You will also see what is imported automatically, how to fix name conflicts like java.util.Date versus java.sql.Date, and how to import classes between your own packages.


Java import Statement Syntax

An import statement goes after the package statement (if there is one) and before the class declaration.

package com.gocourse.demo;      // 1. package statement (optional)

import java.util.ArrayList;     // 2. import statements

public class Demo {             // 3. class declaration
}

There are five forms of import in Java:

FormSyntaxWhat it makes available
Single-type importimport java.util.ArrayList;One class or interface
Type-import-on-demand (wildcard)import java.util.*;Every public type in one package
Single static importimport static java.lang.Math.PI;One static field or method
Static-import-on-demandimport static java.lang.Math.*;Every static member of one class
Module import (Java 25+)import module java.base;Every public type in every package a module exports

Note: An import never copies code into your class and never loads anything at runtime. It only tells the compiler which full name a short name stands for. The compiled .class file always contains full names.


Using a Class Without an Import

Every class can be used without any import by writing its fully qualified name: the package name plus the class name.

public class FullName {
    public static void main(String[] args) {
        // No import: use the fully qualified class name every time
        java.util.ArrayList<String> cities = new java.util.ArrayList<>();
        cities.add("Chennai");
        cities.add("Madurai");
        java.time.LocalDate today = java.time.LocalDate.of(2026, 11, 17);
        System.out.println(cities + " on " + today);
    }
}

Output:

[Chennai, Madurai] on 2026-11-17

How it works:

  • java.util.ArrayList and java.time.LocalDate are the full names of the classes. The compiler finds them without any help.
  • The code works, but repeating long names on every line makes it hard to read. This is the problem imports solve.

Single-Type Import in Java

A single-type import names exactly one class. After it, you can use the short name anywhere in the file.

import java.util.ArrayList;
import java.time.LocalDate;

public class SingleImport {
    public static void main(String[] args) {
        ArrayList<String> cities = new ArrayList<>();
        cities.add("Chennai");
        cities.add("Madurai");
        LocalDate today = LocalDate.of(2026, 11, 17);
        System.out.println(cities + " on " + today);
    }
}

Output:

[Chennai, Madurai] on 2026-11-17

How it works:

  • import java.util.ArrayList; tells the compiler that ArrayList means java.util.ArrayList in this file.
  • The program behaves exactly like the previous one. Only the source code is shorter.
  • Single-type imports are the most common style in real projects, because a reader can see exactly which class each name comes from. IDEs add them for you automatically.

Import Package in Java With a Wildcard

A wildcard import ends with .* and makes every public type in that package available.

import java.util.*;

public class WildcardImport {
    public static void main(String[] args) {
        List<Integer> marks = new ArrayList<>(List.of(78, 92, 65));
        Collections.sort(marks);
        Map<String, Integer> topper = new HashMap<>();
        topper.put("Asha", marks.get(marks.size() - 1));
        System.out.println("Sorted: " + marks);
        System.out.println("Topper: " + topper);
    }
}

Output:

Sorted: [65, 78, 92]
Topper: {Asha=92}

How it works:

  • One line, import java.util.*;, gives access to List, ArrayList, Collections, Map and HashMap.
  • The compiler only resolves the names you actually use. A wildcard import does not make the program bigger or slower.
  • The downside is readability: a reader cannot tell which package Map came from without checking.

Wildcard Imports Do Not Include Sub-Packages

A package and its "sub-package" are completely separate packages. java.util.* does not import anything from java.util.function.

import java.util.*;

public class SubPackage {
    public static void main(String[] args) {
        List<String> names = List.of("asha", "ravi");
        Function<String, String> upper = String::toUpperCase;
        System.out.println(names.stream().map(upper).toList());
    }
}

Output (compile error):

SubPackage.java:6: error: cannot find symbol
        Function<String, String> upper = String::toUpperCase;
        ^
  symbol:   class Function
  location: class SubPackage
1 error

Add a second import for the sub-package:

import java.util.*;
import java.util.function.*;

public class SubPackageFixed {
    public static void main(String[] args) {
        List<String> names = List.of("asha", "ravi");
        Function<String, String> upper = String::toUpperCase;
        System.out.println(names.stream().map(upper).toList());
    }
}

Output:

[ASHA, RAVI]

How it works:

  • Function lives in java.util.function, so it needs its own import.
  • The dot in a package name only reflects folder nesting. As you learned in Package in Java, Java treats each package as an independent unit.

What Java Imports Automatically

You never need to import two kinds of classes:

Automatically availableExample
Everything in java.langString, Math, Integer, System, Thread
Every class in the same package as your fileA Main class using a Helper class in the same package
public class LangDemo {
    public static void main(String[] args) {
        // String, Math, Integer and System all live in java.lang
        String course = "Java";
        int bigger = Math.max(40, 75);
        int parsed = Integer.parseInt("2026");
        System.out.println(course + " " + bigger + " " + parsed);
        System.out.println(String.class.getPackageName());
    }
}

Output:

Java 75 2026
java.lang

How it works:

  • The compiler behaves as if every file starts with import java.lang.*;. That is why String and System work in your very first program.
  • String.class.getPackageName() confirms that String belongs to java.lang.
  • Sub-packages of java.lang, such as java.lang.reflect, are not automatic. You must import them.

Resolving Name Conflicts Between Imports

Two packages can contain classes with the same simple name. The classic example is Date, which exists in both java.util and java.sql. If both packages are imported with wildcards, the short name becomes ambiguous.

import java.util.*;
import java.sql.*;

public class Ambiguous {
    public static void main(String[] args) {
        Date today = new Date();
        System.out.println(today);
    }
}

Output (compile error, shown once for each use of Date):

Ambiguous.java:6: error: reference to Date is ambiguous
        Date today = new Date();
        ^
  both class java.sql.Date in java.sql and class java.util.Date in java.util match

Fixing an Ambiguous Import

A single-type import always wins over wildcard imports. Use it for the class you need most, and write the full name for the other one.

import java.util.*;
import java.sql.*;
import java.util.Date; // single-type import wins over both wildcards

public class DateFixed {
    public static void main(String[] args) {
        Date utilDate = new Date(0);                                 // java.util.Date
        java.sql.Date sqlDate = java.sql.Date.valueOf("2026-11-17"); // full name
        System.out.println(utilDate.getClass().getName());
        System.out.println(sqlDate.getClass().getName() + " " + sqlDate);
    }
}

Output:

java.util.Date
java.sql.Date 2026-11-17

How it works:

  • import java.util.Date; settles which Date the short name refers to in this file.
  • java.sql.Date is still usable through its fully qualified name.
  • You cannot single-import two classes with the same simple name. import java.util.Date; plus import java.sql.Date; is a compile error, so one of them must use the full name.
SituationResult
Two wildcard imports both contain Date, and you use DateCompile error: reference is ambiguous
Wildcard imports both contain Date, but you never use DateCompiles fine
One single-type import of Date plus wildcardsThe single-type import wins
Two single-type imports of different Date classesCompile error: already defined

Static Import in Java

A static import brings in static fields and static methods of a class, so you can call them without the class name. It works only for static members.

import static java.lang.Math.PI;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;

public class StaticImport {
    public static void main(String[] args) {
        double radius = 3.0;
        double area = PI * pow(radius, 2);
        double side = sqrt(area);
        System.out.printf("Area: %.2f%n", area);
        System.out.printf("Square side with same area: %.2f%n", side);
    }
}

Output:

Area: 28.27
Square side with same area: 5.32

How it works:

  • import static java.lang.Math.PI; lets you write PI instead of Math.PI.
  • Method imports use only the method name, with no parentheses: import static java.lang.Math.pow;. All overloads of pow are imported together.
  • The area is 3.14159... × 3² = 28.27, and its square root is 5.32.

Static Wildcard Import

import static ClassName.*; imports every static member of one class. It is common with utility classes such as Collectors.

import static java.util.stream.Collectors.*;
import java.util.List;
import java.util.Map;

public class StaticWildcard {
    public static void main(String[] args) {
        List<String> words = List.of("java", "jar", "module", "map", "import");
        Map<Character, List<String>> byLetter = words.stream()
                .collect(groupingBy(word -> word.charAt(0)));
        String joined = words.stream().collect(joining(", ", "[", "]"));
        System.out.println(byLetter);
        System.out.println(joined);
    }
}

Output:

{i=[import], j=[java, jar], m=[module, map]}
[java, jar, module, map, import]

How it works:

  • groupingBy and joining are static methods of java.util.stream.Collectors. The static wildcard import lets you call them directly.
  • A regular import and a static import are separate: the static import of Collectors.* does not import the Collectors class name itself, and it does not import List or Map.

Note: Use static imports sparingly. max(a, b) alone does not tell the reader it is Math.max. They work best for constants and well-known helpers, such as Collectors or test assertions.


Module Import Declarations (Java 25)

Java 25 added a fifth form: import module. It imports every public type from every package that a module exports. A single line, import module java.base;, covers java.util, java.time, java.io, java.util.function and dozens more packages.

import module java.base;

public class ModuleImport {
    public static void main(String[] args) {
        List<String> names = List.of("Asha", "Ravi");               // java.util
        Function<String, Integer> length = String::length;         // java.util.function
        LocalDate due = LocalDate.of(2026, 12, 1);                 // java.time
        Path report = Path.of("reports", "december.txt");          // java.nio.file
        System.out.println(names.stream().map(length).toList());
        System.out.println("Due " + due + " -> " + report);
    }
}

Output (JDK 25 or newer):

[4, 4]
Due 2026-12-01 -> reports/december.txt

How it works:

  • java.base is the core JDK module. It exports java.util, java.util.function, java.time, java.nio.file and many other packages, so all four types resolve.
  • Unlike java.util.*, a module import does include what you would call "sub-packages", because each one is a separate package exported by the same module.
  • On Windows the path prints as reports\december.txt.
  • If two imported modules contain classes with the same simple name, such as List in java.base and java.desktop, add a single-type import (import java.util.List;) to choose one.

Note: Module imports need JDK 25 or later. On older JDKs, use regular imports. You will learn what modules are in the Java Modules lesson.


Common Import Errors and Their Meaning

A misspelled package name breaks the import and every line that uses the class.

import java.utils.ArrayList;

public class BadImport {
    public static void main(String[] args) {
        ArrayList<String> items = new ArrayList<>();
        System.out.println(items);
    }
}

Output (first two of three errors):

BadImport.java:1: error: package java.utils does not exist
import java.utils.ArrayList;
                 ^
BadImport.java:5: error: cannot find symbol
        ArrayList<String> items = new ArrayList<>();
        ^
  symbol:   class ArrayList
  location: class BadImport

How it works:

  • The package is java.util, not java.utils. Because the import fails, ArrayList is unknown on line 5 too.
  • Always fix the first error first. One correct import usually removes all the follow-up errors.
Error messageLikely cause
package x.y does not existTypo in the package name, or the library/your class is not on the classpath
cannot find symbol ... class XMissing import, or the class is in a sub-package you did not import
reference to X is ambiguousTwo wildcard imports contain a class named X
X is not public in a.b; cannot be accessed from outside packageThe class exists but is package-private (see Access Control in Java)

Real-World Example: Importing From Your Own Packages

Imports work the same way for your own code. This small sales report uses three packages and every import style except module imports.

shop/src/com/gocourse/shop/
├── model/Order.java
├── util/Money.java
└── app/SalesReport.java

model/Order.java:

package com.gocourse.shop.model;

import java.time.LocalDate;

public record Order(String id, String customer, String city, double amount, LocalDate date) { }

util/Money.java:

package com.gocourse.shop.util;

public final class Money {
    public static final double GST_RATE = 0.18;

    private Money() { }

    public static String format(double amount) {
        return String.format("Rs. %,.2f", amount);
    }

    public static double withGst(double amount) {
        return amount * (1 + GST_RATE);
    }
}

app/SalesReport.java:

package com.gocourse.shop.app;

// 1. Your own packages: single-type imports
import com.gocourse.shop.model.Order;

// 2. Static imports from your own utility class
import static com.gocourse.shop.util.Money.GST_RATE;
import static com.gocourse.shop.util.Money.format;
import static com.gocourse.shop.util.Money.withGst;

// 3. JDK packages
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

// 4. Static wildcard import for stream collectors
import static java.util.stream.Collectors.*;

public class SalesReport {
    public static void main(String[] args) {
        List<Order> orders = List.of(
                new Order("A101", "Asha", "Chennai", 1200.00, LocalDate.of(2026, Month.NOVEMBER, 3)),
                new Order("A102", "Ravi", "Madurai", 850.50, LocalDate.of(2026, Month.NOVEMBER, 5)),
                new Order("A103", "Meena", "Chennai", 2300.00, LocalDate.of(2026, Month.NOVEMBER, 9)),
                new Order("A104", "Karthik", "Coimbatore", 640.00, LocalDate.of(2026, Month.NOVEMBER, 12)));

        Map<String, Double> salesByCity = orders.stream()
                .collect(groupingBy(Order::city, TreeMap::new, summingDouble(Order::amount)));

        String customers = orders.stream().map(Order::customer).collect(joining(", "));
        double total = orders.stream().mapToDouble(Order::amount).sum();

        System.out.println("Customers: " + customers);
        salesByCity.forEach((city, amount) -> System.out.println(city + ": " + format(amount)));
        System.out.println("Total: " + format(total));
        System.out.printf("Total with %.0f%% GST: %s%n", GST_RATE * 100, format(withGst(total)));
    }
}

Compile and run from the shop folder:

javac -d out $(find src -name "*.java")
java -cp out com.gocourse.shop.app.SalesReport

Output:

Customers: Asha, Ravi, Meena, Karthik
Chennai: Rs. 3,500.00
Coimbatore: Rs. 640.00
Madurai: Rs. 850.50
Total: Rs. 4,990.50
Total with 18% GST: Rs. 5,888.79

How it works:

  1. Own classes. import com.gocourse.shop.model.Order; works exactly like importing a JDK class. Order must be public for another package to use it.
  2. Own static members. The three static imports let the report call format(...) and withGst(...) and read GST_RATE without writing Money. each time.
  3. JDK classes. Order.java imports LocalDate too. Every file needs its own imports; they never carry over from another file.
  4. Collectors. The static wildcard import supplies groupingBy, summingDouble and joining. TreeMap::new keeps the cities in alphabetical order.
  5. The numbers. Chennai has two orders, 1200.00 + 2300.00 = 3500.00. The total is 4990.50, and adding 18% GST gives 5888.79.

To set up the folders and compile commands for a project like this, see Create Package in Java.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Import Package in Java: The import Statement Explained and get answers drawn from it.

Signed-in readers only.