Lesson 6 of 25

User Input & Output

Scanner for Input

The Scanner class reads user input from the console. Import it from java.util.

Example
import java.util.Scanner;

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

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

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

        System.out.print("Enter your GPA: ");
        double gpa = scanner.nextDouble();

        System.out.println("Hello, " + name + "! Age: " + age);

        scanner.close();
    }
}

Output Methods

Java provides several ways to output text to the console.

Example
// println — prints with newline
System.out.println("Hello, World!");

// print — prints without newline
System.out.print("Hello ");
System.out.print("World!");

// printf — formatted output
System.out.printf("Name: %s%n", "Alice");
System.out.printf("Score: %d/100%n", 95);
System.out.printf("Price: $%.2f%n", 19.99);
System.out.printf("Hex: %x%n", 255);  // ff