← Back to Chapters

Java Import Statement

? Java Import Statement

? Quick Overview

In Java, the import statement is used to access predefined classes, interfaces, and packages. It allows programmers to use built-in Java libraries or user-defined packages without writing full package paths every time.

? Key Concepts

  • Used to access classes from other packages
  • Written at the top of a Java file
  • Improves code readability and maintainability
  • Supports single-class and wildcard imports

? Syntax / Theory

The import statement comes after the package declaration (if any) and before the class definition. Java provides thousands of built-in classes inside packages like java.util, java.io, and java.lang.

? View Code Example
// Importing a single class from java.util package
import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
    }
}

? Code Examples

? View Code Example
// Importing all classes from a package using wildcard
import java.util.*;

public class WildcardExample {
    public static void main(String[] args) {
        ArrayList list = new ArrayList<>();
    }
}

? Live Output / Explanation

Explanation

The compiler uses the import statement to locate the required class definitions. Without importing, you would need to write the full package path like java.util.Scanner every time.

? Interactive Challenge: Fix the Bug

The code below uses the Random class but is missing an import. Click the correct import statement to fix the compiler error!

// ??? Missing Import Statement ??? public class NumberGame { public static void main(String[] args) { Random rand = new Random(); System.out.println(rand.nextInt(100)); } }

? Tips & Best Practices

  • Prefer single-class imports for clarity
  • Avoid unnecessary wildcard imports
  • java.lang package is imported automatically
  • Keep imports organized and minimal

? Try It Yourself

  • Create a program using ArrayList with and without import
  • Experiment with multiple import statements
  • Remove an import and observe compiler errors