Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import package.* vs import package.SpecificType [duplicate]

Would it suppose any difference regarding overhead to write an import loading all the types within one package (import java.*); than just a specific type (i.e. import java.lang.ClassLoader)? Would the second one be a more advisable way to use than the other one?

like image 285
Juan Carlos Blanco Martínez Avatar asked Oct 09 '08 14:10

Juan Carlos Blanco Martínez


People also ask

Why is it better to avoid * in import statements in Java?

Wildcard imports tell java compiler to search for class names in the given package. Hence, using wild card imports, the compile-time performance may lower a bit.

What is the significance of * in import package?

Answer. The asterisk(*) sign indicates that all the classes in the imported package can be used in the program.

What does * mean in Java imports?

import is a Java keyword. It declares a Java class to use in the code below the import statement. Once a Java class is declared, then the class name can be used in the code without specifying the package the class belongs to. Use the '*' character to declare all the classes belonging to the package.

Do wildcard imports affect performance?

There is no performance difference between a specific import and a wildcard import declaration. The information for the classes in imported package is not read in at compile time or run time unless the class is used in the program.


1 Answers

Take a look at the java API, and you'll see many classes and interfaces with the same name in different packages.

For example:

java.lang.reflect.Array java.sql.Array 

So, if you import java.lang.reflect.* and java.sql.* you'll have a collision on the Array type, and have to fully qualify them in your code.

Importing specific classes instead will save you this hassle.

like image 134
Chris Cudmore Avatar answered Sep 20 '22 15:09

Chris Cudmore