Bird
Raised Fist0
Javaprogramming~10 mins

Reading integer input in Java - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Reading integer input
Start Program
↓
Create Scanner
↓
Wait for User Input
↓
Read Input as Integer
↓
Store Integer
↓
Use Integer
↓
End Program
The program starts, creates a Scanner to read input, waits for user input, reads it as an integer, stores it, and then uses it.
Execution Sample
Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        System.out.println(num);
    }
}
This code reads an integer from the user and prints it.
Execution Table
StepActionInput/ValueVariable StateOutput
1Create Scanner objectN/Asc = Scanner(System.in)N/A
2Wait for user inputUser types '42' and presses EnterN/AN/A
3Read integer input42num = 42N/A
4Print the integerN/Anum = 4242
5Program endsN/Anum = 42N/A
💡 Program ends after printing the integer input.
Variable Tracker
VariableStartAfter Step 3Final
scnullScanner(System.in)Scanner(System.in)
numundefined4242
Key Moments - 3 Insights
Why do we need to create a Scanner object before reading input?
The Scanner object connects the program to the keyboard input stream. Without it, the program cannot read what the user types. See execution_table step 1.
What happens if the user types something that is not an integer?
The program will throw an InputMismatchException because nextInt() expects an integer. This is not shown in the table but is important to handle in real programs.
Why do we store the input in a variable?
Storing the input in a variable like 'num' lets us use the number later in the program. See execution_table step 3 where 'num' gets the value 42.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'num' after step 3?
Aundefined
Bnull
C42
D0
💡 Hint
Check the 'Variable State' column at step 3 in the execution_table.
At which step does the program print the user's input?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look for the 'Print the integer' action in the execution_table.
If the user types '100' instead of '42', what changes in the variable tracker?
A'num' changes to 100 after step 3
B'sc' changes to 100 after step 3
C'num' remains undefined
D'sc' becomes null
💡 Hint
The variable 'num' stores the input value, see variable_tracker.
Concept Snapshot
Reading integer input in Java:
1. Import Scanner: import java.util.Scanner;
2. Create Scanner: Scanner sc = new Scanner(System.in);
3. Read int: int num = sc.nextInt();
4. Use 'num' as needed.
Remember: nextInt() reads only integers and throws error on invalid input.
Full Transcript
This example shows how to read an integer input from the user in Java. First, the program creates a Scanner object connected to the keyboard. Then it waits for the user to type a number and press Enter. The nextInt() method reads the typed number and stores it in the variable 'num'. Finally, the program prints the number back to the screen. The execution table traces each step, showing how variables change and when output happens. Key points include creating the Scanner before reading input and storing the input in a variable for later use. If the user types something not an integer, the program will throw an error. This simple flow helps beginners understand how input works in Java.

Practice

(1/5)
1.

Which Java class is commonly used to read integer input from the user?

easy
A. FileReader
B. BufferedReader
C. Scanner
D. PrintWriter

Solution

  1. Step 1: Identify the class for input reading

    The Scanner class is designed to read input from various sources including user input.
  2. Step 2: Confirm the class for integer input

    Scanner provides the nextInt() method to read integers specifically.
  3. Final Answer:

    Scanner -> Option C
  4. Quick Check:

    Input class = Scanner [OK]
Hint: Use Scanner class to read integers easily [OK]
Common Mistakes:
  • Confusing Scanner with FileReader which reads files
  • Using PrintWriter which is for output, not input
  • Thinking BufferedReader reads integers directly without parsing
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.console());
B. Scanner input = new Scanner(System.out);
C. Scanner input = new Scanner(System.err);
D. Scanner input = new Scanner(System.in);

Solution

  1. Step 1: Understand input source for Scanner

    To read user input from the keyboard, System.in is used as the input stream.
  2. Step 2: Match correct Scanner constructor

    The correct syntax is new Scanner(System.in). Other options use output or error streams, which are incorrect.
  3. Final Answer:

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

    Keyboard input = System.in [OK]
Hint: Use System.in with Scanner for keyboard input [OK]
Common Mistakes:
  • Using System.out or System.err instead of System.in
  • Trying to use System.console() which returns Console, not InputStream
  • Forgetting to import java.util.Scanner
3.

What will be the output of the following Java code if the user enters 42?

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        System.out.println(num + 10);
        sc.close();
    }
}
medium
A. 52
B. 42
C. 10
D. Error at runtime

Solution

  1. Step 1: Read integer input

    The program reads an integer from the user using nextInt(). User inputs 42, so num = 42.
  2. Step 2: Add 10 and print result

    The program prints num + 10, which is 42 + 10 = 52.
  3. Final Answer:

    52 -> Option A
  4. Quick Check:

    42 + 10 = 52 [OK]
Hint: Add 10 to input number and print [OK]
Common Mistakes:
  • Printing input without adding 10
  • Forgetting to close Scanner (not an error but good practice)
  • Assuming input is string, causing error
4.

Identify the error in the following code snippet that reads an integer from the user:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int number = sc.nextLine();
        System.out.println(number);
        sc.close();
    }
}
medium
A. Scanner object is not closed properly.
B. Using nextLine() to read an integer causes a type mismatch error.
C. Missing import statement for Scanner.
D. System.out.println() cannot print integers.

Solution

  1. Step 1: Check method used to read input

    The code uses nextLine() which returns a String, but tries to assign it to an int variable.
  2. Step 2: Understand type mismatch

    Assigning a String to an int variable causes a compile-time error. The correct method to read an int is nextInt().
  3. Final Answer:

    Using nextLine() to read an integer causes a type mismatch error. -> Option B
  4. Quick Check:

    nextLine() returns String, not int [OK]
Hint: Use nextInt() to read integers, not nextLine() [OK]
Common Mistakes:
  • Using nextLine() instead of nextInt() for integers
  • Ignoring type mismatch errors
  • Not closing Scanner (though not the main error here)
5.

You want to read two integers from the user and print their sum. Which code snippet correctly does this?

?
hard
A. Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println(a + b); sc.close();
B. Scanner sc = new Scanner(System.in); int a = Integer.parseInt(sc.nextLine()); int b = sc.nextLine(); System.out.println(a + b);
C. Scanner sc = new Scanner(System.in); String a = sc.nextLine(); String b = sc.nextLine(); System.out.println(a + b); sc.close();
D. Scanner sc = new Scanner(System.in); int a = sc.nextInt(); String b = sc.nextLine(); System.out.println(a + b); sc.close();

Solution

  1. Step 1: Identify the correct code for reading two integers

    Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println(a + b); sc.close(); uses sc.nextInt() twice to read integers directly, handling whitespace or newlines, then prints their sum.
  2. Step 2: Eliminate incorrect options

    A: Compile error - int b = sc.nextLine(); (String to int).
    C: Concatenates strings ("1" + "2" = "12").
    D: nextLine() after nextInt() reads leftover newline (b = "", e.g., 5 + "" = "5").
  3. Final Answer:

    Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println(a + b); sc.close(); -> Option A
  4. Quick Check:

    Two nextInt() reads ints correctly [OK]
Hint: Use nextInt() for integer input reliably [OK]
Common Mistakes:
  • Mixing nextInt() and nextLine() causing input skipping
  • Adding strings instead of integers
  • Not closing Scanner after use
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