Bird
Raised Fist0
Javaprogramming~10 mins

Using Scanner class in Java - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Using Scanner class
Start Program
↓
Create Scanner object
↓
Prompt user for input
↓
Wait for user input
↓
Read input using Scanner
↓
Store input in variable
↓
Use input in program
↓
Close Scanner
↓
End Program
The program creates a Scanner to read user input, waits for input, stores it, uses it, then closes the Scanner.
Execution Sample
Java
import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        System.out.println("Hello, " + name + "!");
        sc.close();
    }
}
This code asks the user to enter their name, reads it using Scanner, then greets the user.
Execution Table
StepActionEvaluationResult
1Create Scanner object scsc = new Scanner(System.in)Scanner ready to read input
2Print promptSystem.out.printDisplays: Enter your name:
3Wait for user inputUser types 'Alice' and presses EnterInput buffer has 'Alice'
4Read input with sc.nextLine()Reads 'Alice'name = 'Alice'
5Print greetingSystem.out.println("Hello, " + name + "!")Displays: Hello, Alice!
6Close Scannersc.close()Scanner closed
7Program endsNo more codeProgram terminates
💡 Program ends after greeting and closing Scanner
Variable Tracker
VariableStartAfter Step 4Final
scnullScanner(System.in)closed Scanner
namenull"Alice""Alice"
Key Moments - 3 Insights
Why do we need to close the Scanner?
Closing the Scanner frees system resources. See step 6 in execution_table where sc.close() is called.
What happens if the user types nothing and presses Enter?
sc.nextLine() reads an empty string "" and stores it in name. This is shown in step 4 where input is read.
Why do we use nextLine() instead of next()?
nextLine() reads the whole line including spaces, while next() reads only until the first space. This ensures full input is captured as in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'name' after step 4?
A"Hello"
B"Alice"
Cnull
DScanner object
💡 Hint
Check the 'Result' column in row for step 4 in execution_table.
At which step is the Scanner closed?
AStep 2
BStep 3
CStep 6
DStep 7
💡 Hint
Look for the action 'Close Scanner' in execution_table.
If the user inputs 'Bob Smith', which method ensures the full name is read?
Asc.nextLine()
Bsc.next()
Csc.nextInt()
Dsc.close()
💡 Hint
Refer to key_moments about difference between next() and nextLine().
Concept Snapshot
Using Scanner class in Java:
- Import java.util.Scanner
- Create Scanner with System.in
- Use methods like nextLine() to read input
- Store input in variables
- Close Scanner after use
- Scanner reads user input from keyboard
Full Transcript
This example shows how to use the Scanner class in Java to read user input. First, we create a Scanner object connected to System.in, which is the keyboard input. Then, we prompt the user to enter their name. The program waits until the user types something and presses Enter. Using sc.nextLine(), the program reads the entire line of input and stores it in the variable 'name'. Next, it prints a greeting using the input. Finally, the Scanner is closed to free resources, and the program ends.

Practice

(1/5)
1. What is the primary purpose of the Scanner class in Java?
easy
A. To write output to the console
B. To handle file operations
C. To create graphical user interfaces
D. To read input from the user

Solution

  1. Step 1: Understand Scanner's role

    The Scanner class is designed to read input from various sources, commonly from the user via the keyboard.
  2. Step 2: Differentiate from other classes

    Writing output is done by System.out, GUI creation uses other libraries, and file handling uses classes like FileReader.
  3. Final Answer:

    To read input from the user -> Option D
  4. Quick Check:

    Scanner reads input = B [OK]
Hint: Scanner reads user input from keyboard easily [OK]
Common Mistakes:
  • Confusing Scanner with output classes
  • Thinking Scanner creates GUI
  • Assuming Scanner handles files only
2. Which of the following is the correct way to create a Scanner object to read from the keyboard?
easy
A. Scanner input = new Scanner(System.in);
B. Scanner input = new Scanner(System.out);
C. Scanner input = new Scanner(System.err);
D. Scanner input = new Scanner(System.in.read());

Solution

  1. Step 1: Identify correct Scanner constructor

    The Scanner constructor requires an InputStream to read input. System.in is the standard input stream (keyboard).
  2. Step 2: Check other options

    System.out and System.err are output streams, not input. System.in.read() returns an int, not an InputStream.
  3. Final Answer:

    Scanner input = new Scanner(System.in); -> Option A
  4. Quick Check:

    Use System.in for input Scanner [OK]
Hint: Use System.in to read keyboard input with Scanner [OK]
Common Mistakes:
  • Using System.out or System.err instead of System.in
  • Passing System.in.read() which is an int, not InputStream
  • Missing 'new' keyword
3. What will be the output of the following code if the user inputs the number 25?
import java.util.Scanner;
public class Test {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();
    System.out.println(num * 2);
    sc.close();
  }
}
medium
A. Error at runtime
B. 25
C. 50
D. 0

Solution

  1. Step 1: Understand input reading

    The program reads an integer from the user using nextInt(). User inputs 25, so num = 25.
  2. Step 2: Calculate output

    The program prints num * 2, which is 25 * 2 = 50.
  3. Final Answer:

    50 -> Option C
  4. Quick Check:

    Input 25 * 2 = 50 [OK]
Hint: Multiply input number by 2 to get output [OK]
Common Mistakes:
  • Confusing input with output
  • Forgetting to multiply by 2
  • Not closing Scanner (though not causing output error)
4. Identify the error in the following code snippet:
import java.util.Scanner;
public class Demo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter your name:");
    String name = sc.nextInt();
    System.out.println("Hello, " + name);
    sc.close();
  }
}
medium
A. Not closing the Scanner
B. Using nextInt() to read a String
C. Missing import statement for Scanner
D. Incorrect print statement syntax

Solution

  1. Step 1: Check input method used

    The code uses nextInt() to read the user's name, which is a String, not an integer.
  2. Step 2: Identify correct method

    To read a String, nextLine() or next() should be used instead of nextInt().
  3. Final Answer:

    Using nextInt() to read a String -> Option B
  4. Quick Check:

    Use nextLine() for String input, not nextInt() [OK]
Hint: Use nextLine() for strings, nextInt() for numbers [OK]
Common Mistakes:
  • Using nextInt() for String input
  • Ignoring Scanner import
  • Not closing Scanner (not error here)
  • Misunderstanding print syntax
5. You want to read a full line of text including spaces from the user after reading an integer using Scanner. Which sequence of method calls correctly handles this without skipping input?
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
// What next?
hard
A. sc.nextLine(); String name = sc.nextLine();
B. String name = sc.nextLine();
C. sc.next(); String name = sc.nextLine();
D. sc.nextInt(); String name = sc.nextLine();

Solution

  1. Step 1: Understand Scanner behavior after nextInt()

    After nextInt(), the newline character remains in the input buffer, so a direct nextLine() reads that leftover newline.
  2. Step 2: Consume leftover newline before reading full line

    Calling sc.nextLine() once consumes the leftover newline, then the next nextLine() reads the actual full line input.
  3. Final Answer:

    sc.nextLine(); String name = sc.nextLine(); -> Option A
  4. Quick Check:

    Consume newline with nextLine() before reading full line [OK]
Hint: Call nextLine() twice after nextInt() to read full line [OK]
Common Mistakes:
  • Skipping the first nextLine() to consume newline
  • Using next() which reads only one word
  • Calling nextInt() again unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard