Skip to main content

Section 4.1 Worked Example: Create Instance of Scanner

Subgoals for using objects (creating instances).

  1. Declare variable of appropriate class datatype.
  2. Assign to variable: keyword new, followed by class name, followed by ().
  3. Determine whether parameter(s) are appropriate (API)
    1. Number of parameters
    2. Data types of the parameters

Subsection 4.1.1

You can watch this video or read through the content below it.
The following Java code declares and instantiates a variable that will be used to read input from the user.

Subsection 4.1.2 SG1: Declare variable of appropriate class datatype.

In the code block below, the variable name sysinScanner was selected to better describe what we are going to do with this Scanner, which will become more clear in SG3.
Scanner sysinScanner;

Subsection 4.1.3 SG2: Assign to variable:  keyword new, followed by class name, followed by ().

sysinScanner = new Scanner();

Subsection 4.1.4 SG3: Determine whether parameter(s) are appropriate (API)

The figure below shows the Java documentation, so we can determine what parameter(s) we need. Most of the ways to construct a Scanner require exactly 1 parameter, an object that represents the source of input data. We’ll use the standard system input from the console System.in.
Figure 4.1.1.
So the final code looks like this:
Scanner sysinScanner;
SysinScanner = new Scanner(System.in);
Library classes are pre-written classes available for use in your programs. When using these library classes, you often will need to add an import statement to your program to ensure that the program has access to the library class. Notice in the ActiveCode box below, we have added the appropriate import statement for using the Scanner class.

Practice Pages.

You have attempted of activities on this page.