Java:Java Input and Output: Scanner, System.out, and printf
Java•Input/Output

Java Input and Output: Scanner, System.out, and printf

Learn formatted output with printf format specifiers (%s, %d, %.2f) and tokenized input with Scanner.

Syntax

Scanner scanner = new Scanner(System.in); System.out.printf("Value: %.2f\n", val);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
System.out.printf()MethodOutputs formatted string with format specifiers.
ScannerClassParses primitive types and strings using regular expressions.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Simulating input stream reading
        String simulatedInput = "Compilra 8080 99.85";
        Scanner scanner = new Scanner(simulatedInput);

        String app = scanner.next();
        int port = scanner.nextInt();
        double uptime = scanner.nextDouble();

        System.out.printf("Application: %s%n", app);
        System.out.printf("Port:        %d%n", port);
        System.out.printf("Uptime:      %.2f%%%n", uptime);
        scanner.close();
    }
}
Expected Output:
Application: Compilra
Port:        8080
Uptime:      99.85%

How It Works: Step-by-Step

  • Lines 7-11: Scanner parses tokens into String, int, and double.
  • Lines 13-15: printf formats output with %s, %d, and %.2f.

Key Concepts

  • Scanner automatically tokenizes input separated by whitespace.
  • %n in printf formats system-specific newline (works on Linux and Windows).
  • Always close Scanner when reading system resources to prevent leaks.

Common Mistake: Mixing scanner.nextInt() with scanner.nextLine()

nextInt() does not consume the newline, causing the subsequent nextLine() to read an empty line.

❌ Incorrect
int id = scanner.nextInt();
String text = scanner.nextLine(); // Reads empty string!
✅ Correct
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
String text = scanner.nextLine();

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler