Stage 1: Java fundamentals, lesson 8 of 10

Reading input and formatting output

Beginner3 min readall versions
Explain it forThe essentials plus production detail and pitfalls.

System.out.println prints a line. For tidy output use format strings: System.out.printf("%s is %d years old%n", name, age).

Common format codes: %s text, %d whole numbers, %.2f a decimal with two places, %n a new line, %,d thousands separators, %5d padding to width 5.

To read input, wrap System.in in a Scanner:

  • nextLine() reads a whole line.
  • nextInt() and nextDouble() read numbers.
  • hasNextInt() checks first, so bad input doesn't crash the program.

String.format builds a formatted string without printing it; since Java 15 you can also write "%d items".formatted(n). Since Java 25, IO.readln("Your name: ") reads a line in one call.

Example

Java
import java.util.Scanner;

public class Bill {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Your name: ");
        String name = in.nextLine();

        System.out.print("Items bought: ");
        while (!in.hasNextInt()) {          // keep asking until we get a number
            System.out.print("Please enter a whole number: ");
            in.next();                      // discard the bad input
        }
        int items = in.nextInt();

        double total = items * 249.5;
        System.out.printf("%s, you owe ₹%,.2f for %d items%n", name, total, items);
        // Asha, you owe ₹2,495.00 for 10 items
    }
}

Common mistake

Mixing nextInt() and nextLine() and getting an empty line. Consume the leftover line break, or read lines and parse them.

Under the hood

nextInt() leaves the line break in the buffer, so a following nextLine() returns an empty string. Call nextLine() once to consume it, or read every line with nextLine() and convert with Integer.parseInt. Formatting follows the default locale; pass a Locale when output must be machine-readable. Server applications rarely read the keyboard; they read HTTP requests, files and environment variables.

Check yourself

Which format code prints 3.14159 as 3.14?

How this connects

Where this leads

You've reached the end of this thread. Try a learning path for what's next.

Part of Java from zero.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.