Notifications

No notifications

/Phase 1

I/O — Scanner & System.out

Reading Input, Printing Output 💬

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 format

For 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();

Format Specifiers Cheat Sheet

SpecifierMeaning
%dint / long
%ffloat / double
%.2f2 decimal places
%sString
%cchar
%bboolean
%nplatform newline
%-10sleft-justify width 10
%05dpad with leading zeros

Need Speed? BufferedReader

import 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.

On this page

Detailed Theory

Output — System.out

System.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\n

printf and format

C-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.142

String 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.

Width, Alignment, Padding

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)

Input — Scanner

Scanner 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(); } }

The nextInt() + nextLine() Trap

nextInt() 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

Common Scanner Methods

MethodReads
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?

Reading Until EOF

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.

Reading From a File

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.

Custom Delimiter

Scanner sc = new Scanner("a,b,c,d");
sc.useDelimiter(",");
while (sc.hasNext()) System.out.println(sc.next());

Faster Input — BufferedReader

For 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());

Output Buffering

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();

Try-With-Resources (Auto-Close)

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

Modern Java I/O Quick Hits

// 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: ");

Cheat-Sheet

NeedUse
Print lineSystem.out.println(x);
Formatted printSystem.out.printf("%-10s %d%n", n, x);
Read intsc.nextInt()
Read linesc.nextLine()
Read tokensc.next()
Read until EOFwhile (sc.hasNext())
Fast input (CP)BufferedReader + split or StringTokenizer
Auto-close resourcetry (Scanner sc = ...) { ... }
Read whole fileFiles.readString(Path.of(...))

You can now read anything stdin throws at you, and print neatly. Next: control flow.