Overview
In Java, the import statement is used to bring certain classes or the entire packages, into visibility. As soon as we use the import statement, a class can be referred to, directly by using only its name. Let's take a look at this example.
Example 1 - Using import statement
In this example, we're trying to create an object named ArrayList inside the main method within the class Test, and we save it as Test.java. After examining the code, you may wonder if this Java file will compile successfully. The answer is no. This is because the compiler doesn't recognize ArrayList, resulting in an error.
public class Test{
public static void main (String[] args){
ArrayList myObj = new ArrayList();
}
}
To solve this error, we have 2 solutions. Before that, we need to know which package contain ArrayList class. In this example, ArrayList class is taken from java.util package.
The first solution is by using fully qualified name, where in this case, we just need to add java.util. in front of ArrayList.
public class Test {
public static void main(String[] args) {
ArrayList myObj = new java.util.ArrayList();
}
}
The term "fully qualified name" refers to using the complete package name, such as java.util.ArrayList. While this approach is technically correct, it may reduce code readability when we need to use the ArrayList class multiple times in our program. In such cases, a more practical solution is to use the import statement.
The second solution is by using the import statement. In the provided example, instead of repeatedly using java.util., we can enhance code readability by adding the import statement import java.util.ArrayList before the class definition. This way, the code remains concise, and it compiles successfully.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList myObj = new ArrayList();
}
}