Skip to content
Qyubie Learn
Java tutorialLesson 4 of 18 · tap to see all lessons

Java tutorial · Beginner

Java Input and Output: println, printf, Escape Sequences, and Scanner

Print neat output in Java with print, println, and printf, use escape sequences, and read keyboard input with the Scanner class, including the nextLine trap.

  • Qyubie Learn Editorial Team
  • Published
  • 8 min read

Includes 3 quick checks you can do right here.

Most programs talk to the user: they output results and read input. In Java, output goes through System.out, and keyboard input comes in through the Scanner class. This lesson covers both, plus printf for neat formatting.

By the end of this lesson you will be able to:

  • print with print, println, and printf,
  • format numbers to a fixed number of decimal places,
  • use escape sequences like \n and \t, and
  • read numbers and text from the keyboard with Scanner.

You already know the first two:

  • System.out.println(x) prints x, then moves to a new line.
  • System.out.print(x) prints x and stays on the same line.

The third, printf, prints with a format: a template with placeholders that get filled in.

String name = "Ana";
int units = 21;
double gwa = 1.756;
System.out.printf("%s is taking %d units.%n", name, units);
System.out.printf("GWA: %.2f%n", gwa);

Output:

Ana is taking 21 units.
GWA: 1.76

The placeholders are filled from left to right with the values after the format.

PlaceholderForExample result
%dwhole numbers (int, long)21
%fdecimals (6 places by default)1.756000
%.2fdecimals rounded to 2 places1.76
%sStrings (or anything, as text)Ana
%ca charA
%ba booleantrue
%na new line
%%a literal percent sign%

printf doesn't add a new line by itself, so end the format with %n.

Quick check

What does this print?
double price = 12.5;
System.out.printf("Total: %.2f%n", price * 3);

Lining up columns

A number between % and the letter sets a width. Numbers are right-aligned in that space, and a - left-aligns instead. This makes tables line up:

System.out.printf("%-8s%6s%n", "Name", "Score");
System.out.printf("%-8s%6d%n", "Ana", 95);
System.out.printf("%-8s%6d%n", "Ben", 7);

Output:

Name     Score
Ana         95
Ben          7

Escape sequences

Some characters can't be typed directly inside a String. An escape sequence starts with a backslash:

SequenceMeans
\nnew line
\ttab
\"a double quote inside a String
\'a single quote (needed inside a char)
\\a backslash
System.out.println("Line one\nLine two");
System.out.println("She said \"Good job!\"");
System.out.println("Path: C:\\Users\\Ana");

Output:

Line one
Line two
She said "Good job!"
Path: C:\Users\Ana

Quick check

How many lines does this print?
System.out.print("A\nB");
System.out.println("C\nD");

Reading input with Scanner

Scanner lives in the java.util package, so you import it at the top of the file. Then you create one Scanner connected to the keyboard, System.in, and call its methods to read values.

import java.util.Scanner;

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

        System.out.print("Name: ");
        String name = in.nextLine();
        System.out.print("Age: ");
        int age = in.nextInt();

        System.out.println("Hi " + name + ", next year you'll be " + (age + 1) + ".");
        in.close();
    }
}

When you run it and type Ana, press Enter, then type 19 and press Enter, the console shows:

Name: Ana
Age: 19
Hi Ana, next year you'll be 20.

The Scanner methods you'll use most:

MethodReadsExample input
nextInt()a whole number19
nextDouble()a decimal number1.75
next()one word (stops at a space)Ana
nextLine()the rest of the line, spaces includedAna Cruz
nextBoolean()true or falsetrue

import java.util.Scanner; tells the compiler where to find the class. Without it you get cannot find symbol: class Scanner. Classes in java.lang, like String, Math, and System, never need an import.

The nextLine trap

This is the most common Scanner bug in first-year labs:

import java.util.Scanner;

public class Trap {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Age: ");
        int age = in.nextInt();
        System.out.print("Full name: ");
        String name = in.nextLine();   // returns "" right away!
        System.out.println("[" + name + "] is " + age);
    }
}

nextInt() reads the number but leaves the Enter key (\n) waiting in the input. The next nextLine() sees that leftover Enter and immediately returns an empty String, before the user can type a name.

The fix: after nextInt() or nextDouble(), call in.nextLine(); once to throw away the rest of that line:

import java.util.Scanner;

public class Fixed {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int age = in.nextInt();
        in.nextLine();                 // discard the leftover Enter
        String name = in.nextLine();
        System.out.println("[" + name + "] is " + age);
    }
}

Output (typing 19, Enter, then Ana Cruz, Enter):

[Ana Cruz] is 19

Quick check

A program calls in.nextDouble() and then in.nextLine(). The user types 1.75, presses Enter, and the program skips the second question. Why?

Putting it together

A small grade computer: read two quiz scores and print the average to two decimals.

import java.util.Scanner;

public class Average {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int quiz1 = in.nextInt();
        int quiz2 = in.nextInt();
        double average = (quiz1 + quiz2) / 2.0;
        System.out.printf("Average: %.2f%n", average);
    }
}

Output (typing 85 and 92):

Average: 88.50

Dividing by 2.0 instead of 2 keeps the .5. Integer division would give 88.

Common mistakes

  • Forgetting import java.util.Scanner;
  • The nextLine trap. Add an extra nextLine() after nextInt() or nextDouble().
  • Typing letters when the program calls nextInt(). Java throws InputMismatchException.
  • Missing %n in printf, so the next output runs onto the same line.
  • Wrong placeholder: %d with a double throws IllegalFormatConversionException. Use %f or %.2f.

Summary

  • print stays on the line, println ends it, and printf formats with placeholders like %d, %.2f, %s, and %n.
  • Widths such as %-8s and %6d line up columns.
  • Escape sequences: \n, \t, \", \', \\.
  • Scanner in = new Scanner(System.in); reads input with nextInt, nextDouble, next, and nextLine.
  • After nextInt() or nextDouble(), call nextLine() once before reading a full line.

Next lesson: operators and expressions.

References and further reading