How to use imports in Java?
In Java, the import keyword is used to bring classes or class members from other packages. Import statements are typically used at the beginning of a Java source code file.
There are several ways to use import statements.
- Import the entire package.
- import package_name.*;
- :
Example: Use java.util.*; - This statement imports all classes and interfaces from the java.util package.
- Import specific classes or interfaces:
- import package name.class name;
- Example: import java.util.ArrayList;
- This statement imports the ArrayList class from the java.util package.
- Import static members:
- import static package name.class name.member name;
- import the constant PI from the Java.lang.Math class.
- This statement imports the PI constant from the java.lang.Math class.
- Importing classes with the same name:
If there are classes with the same name in two different packages, you can use the import statement to specify the specific class name and package name to resolve the conflict. - import packageName1.className1;
import packageName2.className2; - Example: import the MyClass class from com.example.package1 and com.example.package2.
- This statement imports the MyClass class from both the com.example.package1 package and the com.example.package2 package.
It is important to note that if you want to use classes or interfaces from other packages, you need to import them before using them or refer to them using their fully qualified names.
In addition, the import statement in Java is simply for coding convenience and does not directly affect the execution of the code, it does not incur any additional overhead.