Lesson 4 of 518 minModule progress 0%

Module 2: Output, Input, Variables, and Types

Reading User Input with `Scanner`

Read text and numbers from the user so your programs can become interactive.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-16

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, edited by hand, and checked against current Java 25 documentation and runnable examples.

Learning goals

  • Create a `Scanner` for standard input
  • Read a line of text
  • Read a number and print a response

Why this matters: Once your program can read input, it stops being a fixed demo and starts reacting to the user.

The basic setup: Import java.util.Scanner, create a scanner from System.in, then call methods like nextLine() or nextInt().

Choose the right method: nextLine() reads a full line of text. nextInt() reads an integer. When you start mixing them, be careful about leftover newline characters.

Keep examples small: Early input programs are easier to debug when they ask one or two simple questions.

Runnable examples

Read one line of text

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("What is your name?");
        String name = input.nextLine();
        System.out.println("Hello, " + name);
    }
}

Expected output

If the user types `Mina`, the program prints `Hello, Mina`.

Read an integer

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter your age:");
        int age = input.nextInt();
        System.out.println("Next year you will be " + (age + 1));
    }
}

Expected output

If the user enters `20`, the program prints `Next year you will be 21`.

Common mistakes

Forgetting the import line

Add `import java.util.Scanner;` at the top of the file.

Using `nextInt()` when you really want a full line of text

Use `nextLine()` for full text input such as names or sentences.

Mini exercise

Ask for the user’s favorite food and print a sentence that includes the answer.

Summary

  • `Scanner` reads user input from the console.
  • `nextLine()` reads text and `nextInt()` reads integers.
  • Interactive programs start with small questions and responses.

Next step

Finish the module by converting values between common types safely.

Sources used

Advertisement

Lesson check

Which method reads a full line of text from a `Scanner`?

Next lesson →