Import Statements in Java

In Java, the import statement is used to bring classes or entire packages into scope, allowing them to be referenced without using their fully qualified names. Import statements help in making code more readable and reduce redundancy.

Importing a Single Class:

To import a single class, use the import statement followed by the fully qualified name of the class.


// Importing a single class
import java.util.ArrayList;

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

Importing an Entire Package:

To import all classes from a package, use the import statement followed by the package name followed by a wildcard character (*).


// Importing all classes from a package
import java.util.*;

public class MyMainClass {
  public static void main(String[] args) {
    List<String> myList = new ArrayList<>();
    Map<String, Integer> myMap = new HashMap<>();
  }
}

Using Fully Qualified Names:

Alternatively, you can use fully qualified names without importing classes. This approach is less common but might be used in scenarios where naming conflicts need to be avoided.


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

Static Import:

The import static statement is used to import the static members of a class or interface. This allows using static methods or fields without qualifying them with the class name.


// Importing static members
import static java.lang.Math.*;

public class MyMainClass {
  public static void main(String[] args) {
    double result = sqrt(25);
  }
}

Note:

Import statements in Java simplify code by providing a concise way to reference classes and packages. Choose between importing single classes, entire packages, using fully qualified names, or importing static members based on your needs and coding style.