Last 30 Days
No notifications
Java has three main printing methods on System.out:
System.out.print("no newline");
System.out.println("with newline");
System.out.printf("Pi = %.2f%n", 3.14159); // C-style formatFor input, the simplest tool is Scanner:
import java.util.Scanner;Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
double pi = sc.nextDouble();
String word = sc.next(); // one whitespace-separated word
sc.nextLine(); // consume the newline left over!
String line = sc.nextLine(); // rest of the line
sc.close();
| Specifier | Meaning |
%d | int / long |
%f | float / double |
%.2f | 2 decimal places |
%s | String |
%c | char |
%b | boolean |
%n | platform newline |
%-10s | left-justify width 10 |
%05d | pad with leading zeros |
BufferedReaderimport java.io.*;BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] tokens = br.readLine().split(" ");
Scanner is convenient but slow for big inputs (10⁵+). Switch to BufferedReader for competitive programming.
System.outSystem.out is a PrintStream — every Java program has it pre-wired to stdout.
System.out.print("a"); // a
System.out.print("b"); // ab
System.out.println(); // newline
System.out.println("hello"); // hello\nprintf and formatC-style format strings, type-checked:
System.out.printf("name=%s age=%d pi=%.3f%n", "Asha", 19, 3.14159);
// name=Asha age=19 pi=3.142String s = String.format("x=%-5d y=%-5d", 42, 7); // returns instead of prints
String f = "Total: %.2f".formatted(99.95); // Java 15+ — instance method
> Use %n (platform newline) instead of \n in format strings for cross-platform code.
System.out.printf("%10s %n", "hi"); // hi
(right-justify, width 10)
System.out.printf("%-10s %n", "hi"); // hi
(left-justify)
System.out.printf("%010d %n", 42); // 0000000042
(zero-pad)
System.out.printf("%+d %n", 42); // +42
(always show sign)
System.out.printf("%,d %n", 1_000_000); // 1,000,000
(locale grouping)ScannerScanner is the simplest input class. Construct it once, read with type-specific methods:
import java.util.Scanner;public class InputDemo {
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.printf("Hi %s, age %d%n", name, age);
sc.close();
}
}
nextInt() + nextLine() TrapnextInt() consumes only the number — the trailing newline stays in the buffer. The next nextLine() will read EMPTY.
int n = sc.nextInt();
sc.nextLine(); // ← consume the leftover newline!
String line = sc.nextLine(); // now reads the actual next line| Method | Reads |
nextInt() | one int (skips whitespace) |
nextLong() | one long |
nextDouble() | one double |
next() | one whitespace-separated token |
nextLine() | rest of current line |
hasNext() | is another token available? |
hasNextInt() | is the next token a valid int? |
Scanner sc = new Scanner(System.in);
int sum = 0;
while (sc.hasNextInt()) {
sum += sc.nextInt();
}
System.out.println(sum);> On Windows the EOF key is Ctrl+Z; on macOS/Linux it's Ctrl+D.
import java.io.File;Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
sc.close();
The constructor throws FileNotFoundException — declare throws on main or wrap in try/catch.
Scanner sc = new Scanner("a,b,c,d");
sc.useDelimiter(",");
while (sc.hasNext()) System.out.println(sc.next());BufferedReaderFor 10⁵+ tokens, Scanner is the bottleneck. BufferedReader is ~5–10× faster but you parse manually:
import java.io.*;BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] parts = br.readLine().split(" ");
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(parts[i]);
br.close();
For huge multi-token input, combine BufferedReader with StreamTokenizer or your own StringTokenizer:
import java.util.StringTokenizer;BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
System.out.println flushes after every call — slow when you have 10⁶ writes. Wrap in a PrintWriter:
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
for (int i = 0; i < 1_000_000; i++) pw.println(i);
pw.flush();Scanner and BufferedReader both implement AutoCloseable. Use try-with-resources to ensure they close even on exceptions:
try (Scanner sc = new Scanner(System.in)) {
int n = sc.nextInt();
System.out.println(n * n);
} // sc.close() automatic// Java 11+ — Files API
String all = Files.readString(Path.of("input.txt"));
List<String> lines = Files.readAllLines(Path.of("input.txt"));// Console — for password input (no echo)
Console c = System.console();
char[] pw = c.readPassword("Password: ");
| Need | Use |
| Print line | System.out.println(x); |
| Formatted print | System.out.printf("%-10s %d%n", n, x); |
| Read int | sc.nextInt() |
| Read line | sc.nextLine() |
| Read token | sc.next() |
| Read until EOF | while (sc.hasNext()) |
| Fast input (CP) | BufferedReader + split or StringTokenizer |
| Auto-close resource | try (Scanner sc = ...) { ... } |
| Read whole file | Files.readString(Path.of(...)) |
You can now read anything stdin throws at you, and print neatly. Next: control flow.