LearnFrenzy
Sign in Take a free test

Variables and Data Types · Lesson 7 of 42

Input and Output with Scanner

5 min read Updated Nov 7, 2026 Saurabh Samir

Most practice programs – and almost every coding round – read input and print results. In Java the standard tool for reading from the keyboard is the Scanner class. It is easy to use, with one famous trap that catches nearly every beginner; you'll learn to avoid it here.

In this lesson

  • Reading numbers, words and lines with Scanner
  • The nextInt() + nextLine() trap
  • Validating input with hasNextInt()
  • Formatted output with printf and String.format

Reading input

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.print("Age: ");
        int age = sc.nextInt();
        System.out.print("CGPA: ");
        double cgpa = sc.nextDouble();
        System.out.println(name + " (" + age + ") has CGPA " + cgpa);
    }
}

Output

Name: Meera Nair
Age: 21
CGPA: 8.7
Meera Nair (21) has CGPA 8.7
MethodReads
nextInt(), nextLong(), nextDouble()the next number
next()the next word (stops at a space)
nextLine()the rest of the current line
nextBoolean()true or false
hasNextInt(), hasNextLine()check what comes next without reading it

The nextInt() + nextLine() trap

nextInt() reads the number but leaves the Enter key (the newline) in the input. The next nextLine() immediately reads that empty remainder and returns "".

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Roll no: ");
        int roll = sc.nextInt();
        System.out.print("Full name: ");
        String name = sc.nextLine();          // reads the leftover newline!
        System.out.println("[" + roll + "] [" + name + "]");
    }
}

Output

Roll no: 42
Full name: [42] []

What is in the input buffer

  1. "42⏎Kabir Singh⏎"what the user typed
  2. nextInt() → 42leaves "⏎Kabir Singh⏎"
  3. nextLine() → ""reads up to the first ⏎ – nothing!

Fix it by consuming the leftover newline, or read every line as text and convert it yourself:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Roll no: ");
        int roll = Integer.parseInt(sc.nextLine().trim());   // read the whole line
        System.out.print("Full name: ");
        String name = sc.nextLine();
        System.out.println("[" + roll + "] [" + name + "]");
    }
}

Output

Roll no: 42
Full name: Kabir Singh
[42] [Kabir Singh]

Validating input

If the user types letters where a number is expected, nextInt() throws InputMismatchException. Check first with hasNextInt():

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age;
        while (true) {
            System.out.print("Age: ");
            if (sc.hasNextInt()) {
                age = sc.nextInt();
                if (age > 0 && age < 120) break;
                System.out.println("Enter a realistic age.");
            } else {
                System.out.println("Digits only, please.");
                sc.next();                 // discard the bad word
            }
        }
        System.out.println("Saved: " + age);
    }
}

Output

Age: twenty
Digits only, please.
Age: 250
Enter a realistic age.
Age: 21
Saved: 21

Reading many values

Coding-test inputs usually start with a count, followed by that many numbers:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long sum = 0;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            int x = sc.nextInt();
            sum += x;
            max = Math.max(max, x);
        }
        System.out.println("Sum = " + sum + ", Max = " + max);
    }
}

Output (input: 5 then 4 17 9 23 6)

Sum = 59, Max = 23

Competitive programming tip

Scanner is convenient but slow for very large inputs (10⁵+ numbers). In contests use BufferedReader with StringTokenizer or Integer.parseInt(line.split(" ")[i]), which is several times faster.

Formatted output

public class Main {
    public static void main(String[] args) {
        String[] items = {"Pen", "Notebook", "Bag"};
        int[] qty = {2, 5, 1};
        double[] price = {10, 45.5, 899};

        System.out.printf("%-10s %5s %10s%n", "Item", "Qty", "Amount");
        double total = 0;
        for (int i = 0; i < items.length; i++) {
            double amount = qty[i] * price[i];
            total += amount;
            System.out.printf("%-10s %5d %10.2f%n", items[i], qty[i], amount);
        }
        System.out.printf("%-10s %5s %10.2f%n", "TOTAL", "", total);
        String line = String.format("Paid %,.2f on %s", 1234567.891, "07-11-2026");
        System.out.println(line);
    }
}

Output

Item         Qty     Amount
Pen            2      20.00
Notebook       5     227.50
Bag            1     899.00
TOTAL               1146.50
Paid 1,234,567.89 on 07-11-2026
FormatMeaning
%d, %s, %c, %binteger, string, char, boolean
%.2fdecimal with 2 places
%10s / %-10swidth 10, right / left aligned
%05dpad with zeros to 5 digits
%,dthousands separator
%nnew line (correct on every OS)

Practice

Try it yourself

  1. Read a temperature in Celsius and print Fahrenheit with one decimal place.

    Show solution
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Celsius: ");
            double c = sc.nextDouble();
            System.out.printf("%.1f°F%n", c * 9 / 5 + 32);
        }
    }

    Output

    Celsius: 36.6
    97.9°F
  2. Read a first and last name on one line with next() and print the initials.

    Show solution
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String first = sc.next(), last = sc.next();
            System.out.println(first.charAt(0) + "." + last.charAt(0) + ".");
        }
    }

    Output (input: Ravi Kumar)

    R.K.

Quick check

Why does nextLine() return "" after nextInt()?

nextInt() leaves the newline in the buffer; nextLine() reads up to it and returns an empty string.

What is the difference between next() and nextLine()?

next() reads one word; nextLine() reads the rest of the line including spaces.

How do you print 7 as "007"?

System.out.printf("%03d", 7);

Summary

  • Create one Scanner sc = new Scanner(System.in) and use nextInt, next, nextLine.
  • After nextInt(), consume the newline – or read whole lines and parse them.
  • Validate with hasNextInt(); format output with printf and String.format.

Interview practice: Java basics interview questions.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Popular