Last modified: January 10, 2023
In Java, a package is a collection of related classes. In addition to helping with organization, packages help prevent name conflicts when programmers make multiple classes with the same name. The full name of a class actually includes the package name. For example, the full name of the Scanner class is java.util.Scanner
. If you were to download the Java source code, you would see that the classes are defined in java files inside folders named according to the package names. For example, in the root directory of the Java source code, there is a folder named java
which contains a folder named util
which contains a file named Scanner.java
.
When you want to use a class that is in a different package than the one you are writing code in, you need to either use the full name of the class or you need to import the class. Importing a class tells the compiler that every time you write that class name, you are refering to the class with the full name you imported. It is like when a formal document says something like "Ted McLeod, hereafter known as Ted...".
To import a class, use the import
statement at the very top of your java file above the class declaration.
Example:
import java.util.Scanner; // imports the Scanner class
import javax.swing.JOptionPane; // imports the JOptionPane class
public class MyClass {
public static void main(String[] args) { // String is in the java.lang package so you don't need to import it (see below)
// The compiler knows you mean java.util.Scanner because you imported it
Scanner in = new Scanner(System.in); // System is in the java.lang package so you don't need to import it (see below)
}
}
In the next few lessons, you will explore how to import and use java.util.Scanner
and javax.swing.JOptionPane
to gather user input.
There is one exception to the import rule: You never have to import classes in the java.lang package. That package includes commonly used classes such as String, Math and System. That is why you are able to just use the String class in your code without having to import anything.
You can also import an entire package instead of just a single class. This can be convenient if you are planning to use many classes from the same package. To do this, simply replace the class name with a *. For example, if you were writing code to read and write files, you will likely use several classes from the java.io package, so you could import all the classes in that package by writing:
import java.io.*;