I have a general question regarding imports. Should one use the import statement or just write the packages inline? I myself have adopted a strategy where I will never import using a wildcard and will only import classes if I use them only once. If I use them twice, i will typically import it. Or does it really not matter? I find most of the time I am writing the packages inline, but I was thinking that maybe this is and an incorrect concept.
Personally, I don't import using wildcard. I import only the classes I need. I don't know that I have ever used inline as opposed to import, though. Maybe I am wrong, but my thinking is I would rather import now, even if I only use it once, rather than come back later and need to import if I use the class multiple times.
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
The only reason I ever had to use inline import statement was in a case where I my code used two different classes with the same name but from multiple packages (one standard java class and one from a third party API in my case) Else I prefer to import the classes using import statements.
I always import only the classes that I need, and I don't use the wildcard to import classes. In fact, I let my IDE organise the imports for me. Both Eclipse and NetBeans have the key combination Ctrl + Shift + I to automatically organise the imports.
Using the wildcard with imports introduces a potential future compatibility problem in your code. Suppose that you do import java.util.*; in your code, and that one of your own classes is named Something. Now, a new version of Java comes out, in which there is a new class in the java.util package that also happens to be called Something. If you imported everything from java.util with the wildcard, the new Something from java.util would also be imported. You'll get compiler errors when you'd use that new version of Java, because the Java compiler can't distinguish between your class and the new class in java.util.
One example where you might need to use the fully qualified names of classes are the java.util.Date and java.sql.Date classes. Sometimes you need to use both those Date classes in the same source file, and to distinguish them you need to name them with their package names prefixed.
Jesper Young wrote:I Both Eclipse and NetBeans have the key combination Ctrl + Shift + I to automatically organise the imports.
On Eclipse it is Ctrl+Shift+O for me which is the default (I think)
I agree with both Maneesh and Jesper. I import only what I need (except in quick test classes), and only use inline imports in case of conflicts; e.g. using both java.io.FileFilter and javax.swing.filechooser.FileFilter in one class. In those cases I always inline import the shortest