Quick Question about Imports...

Hey, I wasn’t sure what to look up to find an answer for this so here goes. Why would you write something such as:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

When you could just write:

import java.io.*;

I see a lot of people importing specific classes instead of just using the general import statement, why do they do this and what, if any, is the benefit of doing so?

I think because everything else is included in that file too. Also because we don’t generally type imports, Eclipse does it for us. :slight_smile:

You’ll end up importing too many classes, like Agro said, if you only use JFrame but do import javax.swing.* you’ve imported unnecessary like JPanel and JButton, etc. Look here: http://stackoverflow.com/questions/979057/any-reason-to-clean-up-unused-imports-in-java-other-than-reducing-clutter

If something that you think is better is not used by everyone else, the chances are there is something wrong with it.

QTF
unless you’re on the cutting edge of game development

There is no reason actually. Doing “import java.io.*” doesn’t actually import all the classes at runtime. The JVM is too smart for that. It only imports referenced classes.

The only reason we “list” them out is Agro’s response: Eclipse does it for us and it hides the import list :slight_smile:

I was told that listing all the imports individually slows down compilation or execution, not that this makes much sense. I’m not sure how reliable the source was, and never tested it, but I’ve taken to condensing the imports manually in my Eclipse environment. Am looking forward to the definitive answer, and am too busy/lazy to try and figure or test it out myself. Just tell me what to do. (I’ve got a lot else on my plate, thank you.) :cranky:

ra4king’s statement about the compiler being smart enough not to load unneeded code has a ring of truth to it. :slight_smile:

Java’s import doesn’t do anything at all except shorten names. Every class in your classpath is already available – all import does is make it so you don’t have to prefix it with the package. It has absolutely zero overhead at any time.

as sproingie said.

also, just let your IDE handle it for you. You can probably tell it also to use the star import if for example you use more then two classes from a package.

You only must use direct class imports if you want to use two packages which have some classes which are named the same.

Its more a sign of clarity.

When you read a code from another programmer you can quickly see which specific classes are referenced,
and if anything might be missing, old version etc.
So when I look at source-code at my company, I can quickly see what classes and packages are important to that class.

You basically know what is important and what not to that class.