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, andprintf, - format numbers to a fixed number of decimal places,
- use escape sequences like
\nand\t, and - read numbers and text from the keyboard with
Scanner.
print, println, and printf
You already know the first two:
System.out.println(x)printsx, then moves to a new line.System.out.print(x)printsxand 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.76The placeholders are filled from left to right with the values after the format.
| Placeholder | For | Example result |
|---|---|---|
%d | whole numbers (int, long) | 21 |
%f | decimals (6 places by default) | 1.756000 |
%.2f | decimals rounded to 2 places | 1.76 |
%s | Strings (or anything, as text) | Ana |
%c | a char | A |
%b | a boolean | true |
%n | a new line | |
%% | a literal percent sign | % |
printf doesn't add a new line by itself, so end the format with %n.
Quick check
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 7Escape sequences
Some characters can't be typed directly inside a String. An escape sequence starts with a backslash:
| Sequence | Means |
|---|---|
\n | new line |
\t | tab |
\" | 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\AnaQuick check
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:
| Method | Reads | Example input |
|---|---|---|
nextInt() | a whole number | 19 |
nextDouble() | a decimal number | 1.75 |
next() | one word (stops at a space) | Ana |
nextLine() | the rest of the line, spaces included | Ana Cruz |
nextBoolean() | true or false | true |
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 19Quick check
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.50Dividing 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()afternextInt()ornextDouble(). - Typing letters when the program calls
nextInt(). Java throwsInputMismatchException. - Missing
%ninprintf, so the next output runs onto the same line. - Wrong placeholder:
%dwith adoublethrowsIllegalFormatConversionException. Use%for%.2f.
Summary
printstays on the line,printlnends it, andprintfformats with placeholders like%d,%.2f,%s, and%n.- Widths such as
%-8sand%6dline up columns. - Escape sequences:
\n,\t,\",\',\\. Scanner in = new Scanner(System.in);reads input withnextInt,nextDouble,next, andnextLine.- After
nextInt()ornextDouble(), callnextLine()once before reading a full line.
Next lesson: operators and expressions.