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:
| Parameter | Type | Description |
|---|---|---|
| System.out.printf() | Method | Outputs formatted string with format specifiers. |
| Scanner | Class | Parses primitive types and strings using regular expressions. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java Stdin Input: Scanner nextInt(), nextLine(), and BufferedReader
Read integers and multi-word lines safely in Java OpenJDK 17 using Scanner with pre-supplied stdin without losing lines.
Java Variables and Primitive Data Types with Examples
Declare typed variables in Java including int, double, boolean, String, and local var (Java 10+).
Java String Methods, StringBuilder, and Immutability
Master String methods (split, substring, replace) and mutable StringBuilder for performance.
Java Type Casting: Widening and Narrowing Conversions
Understand implicit widening conversions and explicit narrowing casts in Java.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.