Skip to main content
Java Basics
CHAPTER 06 Beginner

User Input and Output

Updated: May 17, 2026
5 min read

# CHAPTER 6

User Input and Output

1. Introduction

So far, our programs have been one-way streets — they only output information. Real applications are interactive — they ask questions and respond based on the user's answers. In this chapter, we'll learn how to read user input from the keyboard using Java's Scanner class.

2. Learning Objectives

  • Import and use the Scanner class.
  • Read different data types from the keyboard.
  • Handle common Scanner pitfalls.
  • Format output with printf().
  • Build an interactive application.

3. The Scanner Class

The Scanner class lives in the java.util package and must be imported.
java
12345678910111213
import java.util.Scanner;

public class InputDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        System.out.println("Hello, " + name + "!");
        scanner.close();
    }
}

4. Reading Different Data Types

MethodReads
nextLine()Full line of text (String)
next()Single word (stops at space)
nextInt()Integer
nextDouble()Decimal number
nextBoolean()true or false
nextLong()Long integer
java
12345678910111213141516171819202122
import java.util.Scanner;

public class AllInputTypes {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Enter your age: ");
        int age = sc.nextInt();
        
        System.out.print("Enter your GPA: ");
        double gpa = sc.nextDouble();
        
        System.out.print("Are you enrolled? (true/false): ");
        boolean enrolled = sc.nextBoolean();
        
        System.out.println("Age: " + age);
        System.out.println("GPA: " + gpa);
        System.out.println("Enrolled: " + enrolled);
        
        sc.close();
    }
}

5. The nextLine() Trap (Critical!)

This is the #1 beginner bug with Scanner:
java
123456789
Scanner sc = new Scanner(System.in);

System.out.print("Enter age: ");
int age = sc.nextInt();        // Reads the number, leaves \n in buffer

System.out.print("Enter name: ");
String name = sc.nextLine();   // Reads the leftover \n — SKIPS INPUT!

System.out.println("Name: " + name); // Prints empty string!

Fix: Add a dummy nextLine() after nextInt() or nextDouble():

java
123
int age = sc.nextInt();
sc.nextLine();  // Consume the leftover newline
String name = sc.nextLine();  // Now reads correctly

6. Formatted Output with printf()

SpecifierTypeExample
%sString"Hello"
%dInteger42
%fFloat/Double3.14
%.2f2 decimal places3.14
%nNew linePlatform-independent
java
1234567
String name = "Alice";
int age = 25;
double gpa = 3.856;

System.out.printf("Name: %s%n", name);
System.out.printf("Age: %d years%n", age);
System.out.printf("GPA: %.2f%n", gpa);  // 3.86 (rounded!)

7. String Concatenation with +

java
12345
String first = "John";
String last = "Doe";
int age = 30;

System.out.println(first + " " + last + " is " + age + " years old.");

8. Mini Project: User Information Form

java
1234567891011121314151617181920212223242526272829303132333435
import java.util.Scanner;

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

        System.out.println("============================");
        System.out.println("   USER REGISTRATION FORM   ");
        System.out.println("============================");

        System.out.print("Full Name: ");
        String name = sc.nextLine();

        System.out.print("Age: ");
        int age = sc.nextInt();
        sc.nextLine(); // Consume newline

        System.out.print("Email: ");
        String email = sc.nextLine();

        System.out.print("GPA: ");
        double gpa = sc.nextDouble();

        System.out.println("\n============================");
        System.out.println("   REGISTRATION SUMMARY     ");
        System.out.println("============================");
        System.out.printf("Name:  %s%n", name);
        System.out.printf("Age:   %d%n", age);
        System.out.printf("Email: %s%n", email);
        System.out.printf("GPA:   %.2f%n", gpa);
        System.out.println("============================");

        sc.close();
    }
}

9. Common Mistakes

  • Forgetting to import Scanner: import java.util.Scanner; is required.
  • The nextLine() trap: Always consume the dangling newline after nextInt() or nextDouble().
  • Not closing the Scanner: Always call scanner.close() to prevent resource leaks.
  • InputMismatchException: Entering text when nextInt() expects a number crashes the program.

10. Best Practices

  • Always close your Scanner when done.
  • Use sc.nextLine() after numeric reads to prevent input skipping.
  • Validate input when possible (we'll learn exception handling later).
  • Use printf() for clean, aligned output formatting.

11. Exercises

  1. 1. Write a program that asks for two numbers and prints their sum, difference, product, and quotient.
  1. 2. Build a "Mad Libs" style game that asks for a noun, adjective, and verb, then constructs a funny sentence.
  1. 3. Create a temperature converter that asks for Fahrenheit and converts to Celsius.

12. MCQ Quiz with Answers

Question 1

Which class is used for user input?

Question 2

Which package contains Scanner?

Question 3

Which method reads a full line?

Question 4

What does %d represent in printf?

Question 5

What does %.2f do?

Question 6

What happens if you type "hello" when nextInt() is called?

Question 7

next() stops reading at:

Question 8

How to fix the nextLine() skipping issue?

Question 9

What does scanner.close() do?

Question 10

System.in represents:

13. Interview Questions

  • Q: What is the difference between next() and nextLine()?
  • Q: Explain the newline buffer issue with Scanner and how to fix it.
  • Q: What is InputMismatchException and when does it occur?

14. Summary

The Scanner class enables interactive Java programs by reading user input from the keyboard. Different methods read different data types. The nextLine() trap is the most common beginner bug — always consume the trailing newline after numeric reads. Use printf() for formatted output.

15. Next Chapter Recommendation

Now that your programs are interactive, in Chapter 7: Conditional Statements, we'll teach the program to make decisions using if, else, switch, and build a grade evaluation system.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·