Console Input & Output in Java
Master printing to the console with System.out and reading user input (text + numbers) using the Scanner class and command-line arguments.
Console Output Basics
Console output means showing text on the terminal screen. Java provides `System.out.println()`, `System.out.print()`, and `System.out.printf()` to print messages and values. These are extremely useful for debugging and building CLI apps.
1. System.out.println() (Print with Newline)
Use this when you want to print something and automatically move to the next line. Every `System.out.println()` ends with a newline.
2. System.out.print() (No Newline)
Use `System.out.print()` when you want to print without moving to the next line.
3. System.out.printf() (Formatted Output)
Use `printf()` to print with format specifiers like `%s` (String), `%d` (int), `%f` (float).
Formatted Console Output
Many CLI programs print clean tables. Java's `String.format()` and `printf()` let you align columns using format specifiers with width modifiers like `%-15s` (left-align, 15 chars wide) and `%10d` (right-align, 10 chars wide).
1. String.format() Basics
`String.format()` works like `printf` but returns a String instead of printing directly.
2. Print a Simple Table (Aligned Columns)
Loop over data and print each row with fixed-width columns so everything looks clean.
Console Input (Reading User Data)
Console input means the user types something in the terminal and your program reads it. Java supports: 1) `Scanner` (interactive input — asks questions like a form) 2) Command-line arguments via `args[]` in the `main` method
1. Scanner — Read a String
`Scanner` reads from `System.in` (keyboard). Use `nextLine()` to read a full line of text.
2. Scanner — Read a Number
Use `nextInt()` or `nextDouble()` to read numbers directly. Always validate to avoid crashes.
3. Scanner — Read Multiple Values
Read several values in one line, split by spaces. Use `split()` and parse each token.
4. Command-Line Arguments (args[])
Pass values directly when running the program: `java Main Alice 22`. They arrive in the `args` array of `main`.