Skip to content

Imports

This content is for Java. Switch to the latest version for up-to-date documentation.

Imports allow you to use classes and interfaces from other packages in your Java code without having to use their fully qualified names.

import package.name.ClassName; // Import a specific class
import package.name.*; // Import all classes from a package
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
System.out.println(list);
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
HashMap<String, Integer> map = new HashMap<>();
Scanner scanner = new Scanner(System.in);
}
}

Importing an Entire Package (Wildcard Import)

Section titled “Importing an Entire Package (Wildcard Import)”

To import all classes from a package:

import java.util.*;
public class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
HashMap<String, Integer> map = new HashMap<>();
}
}

Java automatically imports:

  • java.lang.* package (includes String, System, Object, etc.)
  • Classes from the current package
// These imports are not needed:
// import java.lang.String;
// import java.lang.System;
public class Example {
public static void main(String[] args) {
String text = "Hello World";
System.out.println(text);
}
}

You can use a class without importing it by using its fully qualified name:

public class Example {
public static void main(String[] args) {
java.util.ArrayList<String> list = new java.util.ArrayList<>();
list.add("Hello");
System.out.println(list);
}
}

Static imports allow you to access static members of a class without class qualification:

import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
import static java.lang.System.out;
public class Example {
public static void main(String[] args) {
double radius = 5.0;
double area = PI * radius * radius;
out.println("Area: " + area);
out.println("Square root of area: " + sqrt(area));
}
}
  1. Imports do not include sub-packages
  2. You cannot use wildcard imports to import classes from multiple packages
  3. If there are naming conflicts, you must use fully qualified names
  4. Import statements should appear after the package declaration but before any class declarations
  5. Avoid using wildcard imports when only a few classes from a package are needed
  6. Most IDEs will automatically manage imports for you

If two packages have classes with the same name, you need to use fully qualified names for at least one of them:

import java.util.Date;
public class Example {
public static void main(String[] args) {
Date utilDate = new Date(); // java.util.Date
java.sql.Date sqlDate = new java.sql.Date(0); // java.sql.Date with fully qualified name
}
}
Built with passion by Ngineer Lab