Import Statements
Look at the top of Listing 3.1, and you will see an import line. Import lines allow you to use information from other packages. Packages hold many source files together. When you have a large project it makes sense to break it up into smaller packages. In this book we will not create projects larger than a few files, and as a result, will not be using packages. However, Java provides many built-in packages, which we will make use of, using import statements.
The next line is the import statement.
import java.io.*;
Import statements are very important in Java. They allow you to use classes from other packages. These packages may be packages you have created, or they may be Java system packages. In the case of the above import line, we are using a Java system package named “io”. The * on the end specifies that we want to import all of the classes from io.
There are actually two ways you can import. You can import every class in a package, such as I just demonstrated. Or you can only import the classes you are going to actually use. If you examine the above program, you will see that we are using three classes: BufferedReader, InputStream, and IOException. We are also using System, but its automatically available without the need for an import. To import these three classes one by one, you would use the following lines of code:
import java.io.BufferedReader; import java.io.InputStream; import java.io.IOException;
Both of the two methods accomplish exactly the same thing; they will import the necessary classes. It is no less efficient to import all of the classes compared to just the classes you need. So which should you use? This is a controversial topic that has been the topic of debate among experienced Java programmers. Ultimately it just comes down to looks, and individual style. Some programmers think the single line looks better, some like seeing every class you use listed. This is the point at which a student in one of my face-to-face classes would always ask me, well Jeff, which do you prefer?
I will answer that, and I am sure I will get more than a few emails of disapproval. I have seen that as programs grow the number of import statements can get huge if you have each listed. It then becomes hard to maintain and its not really adding anything to the program. Because of this, I always use “.*” imports.




