JOOPs Through Java
All lessons

Unit 2 · Java Fundamentals · 7 min

Taking input with Scanner

The Scanner class reads what the user types on the keyboard so your program can work with real values instead of fixed ones.

Why this matters

A program that always prints the same thing is not very useful. Input makes your programs interactive, and most lab exercises require it.

Syntax

Syntax
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

Example

Java
import java.util.Scanner;

public class Greet {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = sc.nextLine();

        System.out.print("Enter your age: ");
        int age = sc.nextInt();

        System.out.println("Hi " + name + ", next year you will be " + (age + 1));
        sc.close();
    }
}

Output

Enter your name: Ananya Rao
Enter your age: 19
Hi Ananya Rao, next year you will be 20

Step by step

  1. 1`import java.util.Scanner;` brings the Scanner class into your file.
  2. 2`new Scanner(System.in)` creates a Scanner object connected to the keyboard.
  3. 3`nextLine()` reads a full line of text, `nextInt()` reads a whole number.
  4. 4`sc.close()` releases the resource when you are done.

Key points

  • Always import java.util.Scanner
  • nextInt(), nextDouble(), next(), nextLine() read different things
  • nextLine() after nextInt() often reads an empty line — call nextLine() once extra to clear it

Common mistakes

  • Forgetting the import statement
  • Typing text when the program expects a number (InputMismatchException)
  • The classic nextInt() then nextLine() skipping problem

Try it yourself

  • Read two numbers and print their sum.
  • Read a student's name and three marks, then print the total and average.
Open the practice notebook