Importing Classes
In the next node, we'll see how to get input using a Java Class called Scanner. Before we can use the Class however, we need to import it.
import
If you had a class called Blob
in your project, you could use it right away without importing it. However, the Scanner isn't in your project, so you need to tell Java where to find it.
We saw previously that you could import ArrayList with the following line of code at the top of your code :
import java.util.ArrayList;
Similarly, you can import Scanner with this code:
import java.util.Scanner;
The import statement consists of 3 parts: the import
keyword, the Package name, and the Class name.
package
A package is a collection of related Java classes. The standard Java library is organized into many different packages. To import a Class, you need to specify the package that it belongs to so that Java can find it. There could be identically-named classes in different packages, but packages each have their own unique name. java.util is an important package in the standard library that contains a large number of useful classes.
The final part of the import statement specifies the Class to import, which in this case is Scanner
. Notice that the class name is capitalized as always.
You can also get access to all of a package's classes without specifying each Class separately. To do this, you just use an *
to represent any Class. For example,
import java.util.*;
will let you use any Class in java.util
, such as ArrayList and Scanner.
java.lang
Question: We've used the String class many times and never needed to import it. Shouldn't String need to be imported just like ArrayList and Scanner?
Answer: Great question! String is a regular class just like ArrayList. However, it belongs to the package called java.lang, which is so common that Java automatically imports it into all of your code. So it's as if the top of you code begins with the following line:
import java.lang.*;
Task
- Create a new Class called Menu in your Notebook project.
- Import the Scanner class from
java.util
into the Menu file.
Challenge
One day, when browsing through the docs for package java.util
, you notice a useful class called HashMap. Write the code to import it into your project.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
You decide you need many different Classes from the package called java.io
. Write one line of code to import the entire package.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.