What is better: import one by one or .*? - java

I am busy with a little Java program for a school project, and my import list became longer and longer. This made me wonder if it is better to import all at once:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Or to import necessary classes one by one:
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.ComponentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Point;
I can imagine, with really big projects, the import list can become really long. So are there any performance considerations?
Found answer here, link provided by Guo Song:
The import directive is a compiler directive, it tells the compiler where to look for a class and allows to not have to always use fully qualified class names, e.g. java.util.HashMap. But the import directives themselves do not get put into the compiled bytecode files, the compiler compiles the fully qualified name into the .class file.
When used wiithout a wildcard, the directive explicitly tells the compiler to look for one specific file in the classpath. With a wildcard, the directive tells the compiler to look for the named package and to search in that package for possible matches every time any name needs to be matched. The latter version is probably going to take (a bit) longer for the compiler than the former.
In other words, the import directive cannot affect runtime code execution in any way. However, the import directive does affect compilation time. Additionally, I find that using import with wildcards makes the code less readable.
Actually, the cost of import statements question of the month on javaperformancetuning.com perfectly summarize this in its conclusion:
There is no runtime cost from using an import statement
The compilation process can take a little more time with an import statement
The compilation process can take even more time with a wildcard import statement
For improved readability, wildcard import statements are bad practice for anything but >>throwaway classes
The compilation overhead of non-wildcard import statements are minor, but they give readability benefits so best practice is to use them

It will not effect the RUN TIME SPEED of program.
but it will effect COMPILE TIME SPEED of program.
if you import java.sql.* then at the compile time compiler import packages one by one so there is a overhead in compile time
But at run time compiler ignore all the unused import statement that is imported by compiler at compile time so it will not effect RUN TIME speed of your program.
generally it is good to import by full qualified name instead of importing all list ,this will increase readability ,maintainability of your code .
Let's look at a simple case:
import java.util.*;
and
import java.util.ArrayList;
import java.util.List;
//.when we write a program :..
List <String> someList = new ArrayList <String> ();
//...
When the compiler hits the word List, in the first case, it will need to figure out if List exists in that set of classes or not. In the second case, it is already given it explicitly, so its much easier.

In My Opinion , You should import them one by one :
Importing them all will result many imports that you don't need
Simple reason also that you can see them in front of you as makes it easier to you and you can also arrange them and put comments on top for educational purpose or other..

It is better to import them one by one.
This is simply because you may not have code collisions now, but if there is a later update to the package you are importing that adds a new class that has the same name as a class you have personally, written, it will break.
Performance is not really the main issue with this, because it shouldn't make the code run slower, but it may increase the size of your .class files or .jar.
The number of import statements is not really that big of an issue - yes, it may be many lines, but does it really do any damage to the readability of your code? Not really.
I hope this helped.

Related

Is it possible to import several packages at once in Java?

I would like for example to do the following:
import packageA.*, packageB.*;
but the above notation does not work. Is it possible to do this somehow in Java, or do I always have to type:
import packageA.*;
import packageB.*;
?
It is not possible in Java to perform two imports with one import statement.
So yes, you always have to do
import packageA.*;
import packageB.*;
You can find out more about the syntax of import statement in the Java Language Specification section 7.5
There are four different types of import declarations but none of them can import more than one thing per import statement:
ImportDeclaration:
SingleTypeImportDeclaration
TypeImportOnDemandDeclaration
SingleStaticImportDeclaration
StaticImportOnDemandDeclaration
No, it cannot be done.
I don't see why this is such a hardship.
A better solution would be to use an IDE that can add the imports as you need them.
I'd also recommend spelling each one out individually rather than using the star notation, even if you need to import all of them. It documents your intent better, and that IDE can make it transparent to you.

Java.io.*, What does it do exactly? [duplicate]

I was working on a little Java program and was using arrays so I had done:
import java.util.Arrays;
Later I started expanding on what I had previously done and decided I wanted to get input from the user, so at that point I added:
import java.util.Scanner;
Now a thought occurred. I know that I could just do:
import java.util.*
Then I'd just need 1 import line instead of two (or however many I end up needing), but does the wildcard in the import mean that it will import everything from that package regardless of if it's needed or not, or will only the selective functionality be pulled?
My instinct here is to write more code and only include the packages I know I need, but if it doesn't make a difference why would anyone import more levels/packages then they need to? (I'd rather just be lazy and write less code)
Be clear about what import is doing. It does NOT mean loading .class files and byte code.
All import does is allow you to save typing by using short class names.
So if you use java.sql.PreparedStatement in your code, you get to use PreparedStatement when you import java.sql.PreparedStatement. You can write Java code forever without using a single import statement. You'll just have to spell out all the fully-resolved class names.
And the class loader will still bring in byte code from .class files on first use at runtime.
It saves you keystrokes. That's all.
It has nothing to do with class loading.
Personally, I prefer to avoid the * notation. I spell each and every import out. I think it documents my intent better. My IDE is IntelliJ, so I ask it to insert imports on the fly.
Laziness is usually a virtue for developers, but not in this case. Spell them out and have your IDE insert them for you individually.
if you type
import java.util.*;
you'll get to refer to Scanner and List by their short names.
But if you want to do the same for FutureTask and LinkedBlockingQueue you'll have to have this:
import java.util.concurrent.*;
The wildcard imports everything in that package. However, use an IDE like Eclipse and it offers you the possibility to organize the imports.
The wildcard imports all classes and interfaces in that package.
However, the wildcard import does not import other packages that start with the same name.
For example, importing java.xml.* does not import the java.xml.bind package.

Does an import wildcard import everything all the time?

I was working on a little Java program and was using arrays so I had done:
import java.util.Arrays;
Later I started expanding on what I had previously done and decided I wanted to get input from the user, so at that point I added:
import java.util.Scanner;
Now a thought occurred. I know that I could just do:
import java.util.*
Then I'd just need 1 import line instead of two (or however many I end up needing), but does the wildcard in the import mean that it will import everything from that package regardless of if it's needed or not, or will only the selective functionality be pulled?
My instinct here is to write more code and only include the packages I know I need, but if it doesn't make a difference why would anyone import more levels/packages then they need to? (I'd rather just be lazy and write less code)
Be clear about what import is doing. It does NOT mean loading .class files and byte code.
All import does is allow you to save typing by using short class names.
So if you use java.sql.PreparedStatement in your code, you get to use PreparedStatement when you import java.sql.PreparedStatement. You can write Java code forever without using a single import statement. You'll just have to spell out all the fully-resolved class names.
And the class loader will still bring in byte code from .class files on first use at runtime.
It saves you keystrokes. That's all.
It has nothing to do with class loading.
Personally, I prefer to avoid the * notation. I spell each and every import out. I think it documents my intent better. My IDE is IntelliJ, so I ask it to insert imports on the fly.
Laziness is usually a virtue for developers, but not in this case. Spell them out and have your IDE insert them for you individually.
if you type
import java.util.*;
you'll get to refer to Scanner and List by their short names.
But if you want to do the same for FutureTask and LinkedBlockingQueue you'll have to have this:
import java.util.concurrent.*;
The wildcard imports everything in that package. However, use an IDE like Eclipse and it offers you the possibility to organize the imports.
The wildcard imports all classes and interfaces in that package.
However, the wildcard import does not import other packages that start with the same name.
For example, importing java.xml.* does not import the java.xml.bind package.

Difference between complete package import .* and specified class import java? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why is using a wild card with a Java import statement bad?
Ex. 1
import javax.swing.*
JFrame f = new JFrame()
Ex. 2
import javax.swing.JFrame
JFrame f = new JFrame()
Is there any efficiency gain (even the slightest and minimal) in adapting 2) instead of 1) ? How does java does the referencing of packages internally?
The first time the compiler comes across the word JFrame, I presume that it should search for JFrame in complete swing.* package in case of 1)..Else if in case 2), it might probably get hold of the class directly by some indexing or may be key value hashing? So why is this not considered an efficiency gain even if it is tiny? (Please correct me if my presumptions about the internals are wrong)
EDIT :
Sorry for the duplicate.. Answer at Why is using a wild card with a Java import statement bad?
There is no runtime penalty for using import javax.swing.*
and import javax.swing.JFrame in Java. The only different is in compile time, the import package.* will search for whole package to find the correct class' information.
The Single-Type-Import (e.g., import javax.swing.JFrame) increases the readability of the program and it will be very clear which classes have been used.
The Type-Import-on-Demand (e.g. import javax.swing.*) causes the simple names of all public types declared in the package javax.swing to be available within the class and interface declarations of the compilation unit.
the first one will load all classes in the package at the compile time
Ex : 1
import javax.swing.*
JFrame f = new JFrame()
the second will load only class specified at the compile time
Ex: 2
import javax.swing.JFrame
JFrame f = new JFrame()
it will increase the compile time if you use the first approach
The star notation is merely a convenience so you as a programmer don't have to write tons of import statements. The star notation will include all classes of the specific package as a compilation candidate.
Note that in most cases being specific is preferred as it will clearly expresses your intention. Furthermore, modern IDE's will do the tedious bit of import statements for you. So in a way you can consider the star notation rather obsolete.
It has performance issue at compile time as others said (may not be very significant one considering the processing power of current computers). ie., importing * make the compiler need to look in entire package, while importing a specific class allows the compiler to fetch it directly. But it doesn't cause any performance issues at run-time, because all classes will be correctly linked by the compiler after compilation.
It also has something to do with readability. If we import javax.swing.*, it will be difficult for us to know which classes are being used from the package javax.swing. We need to read the program to find it out. But, if we import specific classes like import javax.swing.JFrame, it will help the reader to understand only the specified classes are being used from outside packages. Here we know that only JFrame is used from the package javax.swing without reading the entire program. ie., the one can find the dependencies required by our program easily by looking at the import section.
Another problem is that you may get into naming conflicts. For example, if you do two imports import com.abc.* and import com.xyz.*. Now, assume that both packages contain a class named SomeClass. Then, it put the compiler into an ambiguous situation as to which SomeClass to be imported, and thus it will result in a compile time error.
Apart from that Ex.2 is more explicit and thus clearer, it's also more stable/ compatible.
E.g. consider
import java.awt.*;
import java.util.*;
...
List list;
in pre-collection days. If you run the same code with a jdk version which has collections, the compiler complains as it doesn't know which List to use.
As others said, IDEs will help you organize the import statements.
Yes.
import javax.swing.*
imports all classes within this package.
import javax.swing.JFrame
imports only JFrame class.
I would suggest importing concrete classes.
Regards!

What is the proper style for listing imports in Java?

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 days ago.
Improve this question
Is it better to list each individual piece of a package you're going to need (see #1) or is it better to just import everything from a package (see #2)?
1
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.ColorConvertOp;
2
import java.awt.*;
It's NOT simply a matter of style; import-on-demand can result in code that ceases to compile as new classes are added to existing packages.
Basic idea
(See http://javadude.com/articles/importondemandisevil.html for details.):
import java.awt.*;
import java.util.*;
...
List list;
worked in Java 1.1; as of Java 1.2, the above code will no longer compile.
Import on demand is EVIL because your program can stop compiling when new classes are added to existing packages!
ALWAYS use explicit imports. It's not a matter of style; it's a matter of safety.
This is especially bad if you check in perfectly-compiling code and a year later someone checks it out and tries to compile it with new class libraries.
(Import-on-demand is an example of a really bad programming language feature - no feature should break code when new types are added to a system!)
Use import individually.
It is way lot better for production code to list each and every one of the classes being imported.
While the IDE's do a great job helping you know which classes are being used, it is more readable to know that you're referring to :
java.util.List;
and not
java.awt.List;
and so on.
Additionally it is recommended that you group them by package starting by the core libraries passing by 3rd party and ending with own project libraries:
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.TableModelListener;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import your.own.packagename.here.SomeClass;
import your.own.packagename.here.OtherClass;
Using wildcard is acceptable for small self project/classes. It is faster, but it is not expected to be maintainable. If any other developer is involved, use the first.
The latter is generally considered "bad form". With tool support, there's no excuse for not listing them individually, and it removes any ambiguity.
Mind you, Eclipse by default uses wildcards for static imports, and explicit imports for normal ones. Not sure why it makes that distinction.
edit: the distinction is obvious in hindsight - static imports often refer to static methods, and you can't unambiguously refer to a static method by name (due to overloading). So if it can't be fully unambiguous, you may as well use a wildcard.
I know the question was not about performance but, the cost of import statements question of the month on javaperformancetuning.com perfectly summarize why you should avoid to use wildcards:
(...)
Finally, many people find that using
imports with wildcards makes the
source much less readable, since the
reader also needs to figure out which
package a particular class comes from,
rather than just looking it up in the
import statement.
So the full answer is
There is no runtime cost from using an import statement
The compilation process can take a little more time with an import
statement
The compilation process can take even more time with a wildcard import
statement
For improved readability, wildcard import statements are bad practice for
anything but throwaway classes
The compilation overhead of non-wildcard import statements are
minor, but they give readability
benefits so best practice is to use
them
It is a bad practice to use wilcard import statements, they make the code less readable, just don't do it. The only exception to this rule are static import, for example import static org.junit.Assert.*;. No, I don't want to import each assertXXX individually and I don't find that this harms code readability.
If you list them individually it is easier to detect, when reading code with a simple editor (rather than from inside a dev environment), which package objects come from. When reading code from complex projects this can save significant time. Had an example of that earlier today, in fact, when I was studying code from a large open source project without wanting to load everything into eclipse.
If you use an ide like visual studio it typically takes care of this issue for you, so you don't even need to bother thinking about it.
Most IDEs that I am aware of choose option 1 above. This is consistent with some code analysis tools that I used in the past (like checkstyle), as they consider it bad practice to use the * notation.
The option 1 you listed is preferable but if there are more classes you are importing from say java.awt.image, then its preferable to just have one import java.awt.image.* Most IDE's let you specify the exact count of the number of imports to be used. For eg in IDEA, we can use File->Settings->Code Style->imports In the General tab there is a field Class count to use import with * and default value is 5.
whatever the default of your team's IDE is. that way you can just do an autoformat of your file before committing it.
There is no one right answer here.
The People Who Brought You Eclipse voted for individual imports, since Source/Organize Imports will convert the * form to the specific form.
Import individually, it saves the compiler from having to look through each package for each class and therefore makes things run quicker.

Categories