Input and Output
Input and Output
Almost every program you write this year will read something, compute something, and print something. This tutorial covers the reading and the printing.
The three printing methods
System.out is an object representing standard output. It offers three methods you will use constantly.
println(x)printsxand then a newline.print(x)printsxwith no newline, so the next output continues on the same line.printf(format, values...)prints using a format string, giving you control over width and decimal places.
public class Main {
public static void main(String[] args) {
System.out.println("Each println ends the line.");
System.out.println("So this is on a new line.");
System.out.print("These ");
System.out.print("three ");
System.out.print("calls share a line.");
System.out.println();
String name = "Ravi";
int marks = 78;
System.out.println(name + " scored " + marks);
System.out.println("Sum: " + 2 + 3);
System.out.println("Sum: " + (2 + 3));
System.out.println("Tab\tseparated");
System.out.println("Line one\nLine two");
System.out.println("She said \"hello\"");
}
}
Those two Sum: lines are the classic trap. + is evaluated left to right, so "Sum: " + 2 is already the string Sum: 2, and appending 3 gives Sum: 23. Brackets force the arithmetic first.
The backslash sequences are the same as in C: \n newline, \t tab, \" a literal quote, \\ a literal backslash.
printf and formatting
String concatenation is fine until you need alignment or a fixed number of decimals. printf uses format specifiers, placeholders replaced by the arguments that follow, in order.
| Specifier | Prints |
|---|---|
%d |
An integer |
%f |
A decimal, six places by default |
%.2f |
A decimal rounded to two places |
%s |
A string |
%c |
A single character |
%b |
A boolean |
%n |
A newline |
%% |
A literal percent sign |
public class Main {
public static void main(String[] args) {
String name = "Priya Sharma";
int roll = 101;
double cgpa = 8.6666;
System.out.printf("%s has roll %d and CGPA %.2f%n", name, roll, cgpa);
System.out.printf("%-15s %5s %8s%n", "NAME", "ROLL", "CGPA");
System.out.printf("%-15s %5d %8.2f%n", "Priya Sharma", 101, 8.67);
System.out.printf("%-15s %5d %8.2f%n", "Vikram Singh", 102, 7.15);
System.out.printf("%-15s %5d %8.2f%n", "Ananya Rao", 103, 9.05);
double percentage = 456.0 / 7.0;
System.out.printf("Average: %.3f%n", percentage);
System.out.printf("Rounded: %.0f%n", percentage);
System.out.printf("Scored %d%% of the total%n", 78);
}
}
A number between the % and the letter sets the minimum width, which is how the columns above line up. A minus sign left-aligns instead of right-aligning. Use %n rather than \n in a format string: %n emits whatever the current platform considers a line separator.
Unlike a cast, %.2f rounds, so 8.6666 prints as 8.67.
If you write %d and pass a double, the code compiles and then throws IllegalFormatConversionException when that line runs. The format string is just text as far as the compiler is concerned. Read the specifiers and the arguments together whenever a printf line misbehaves.
Reading input with Scanner
To read from the keyboard, create a Scanner wrapped around System.in. It lives in java.util, so you must import it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your roll number: ");
int roll = sc.nextInt();
System.out.print("Enter your CGPA: ");
double cgpa = sc.nextDouble();
System.out.printf("Roll %d has CGPA %.2f%n", roll, cgpa);
sc.close();
}
}
The methods match the types you want to read:
| Method | Reads |
|---|---|
nextInt() |
An integer |
nextDouble() |
A decimal |
nextLong() |
A long integer |
nextBoolean() |
true or false |
next() |
One word, stopping at whitespace |
nextLine() |
The rest of the current line, including spaces |
The import java.util.Scanner; line must be the first statement in the file, above the class declaration.
The nextLine trap
This is the single most common Java problem in first-year labs, so it is worth understanding rather than memorising.
nextInt() reads the digits you typed and stops right there. The Enter key you pressed leaves a newline sitting in the input buffer, unread. When you then call nextLine(), it reads from the current position to the end of the line, finds that leftover newline immediately, and returns an empty string without waiting for you to type anything.
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");
int age = sc.nextInt();
sc.nextLine(); // consume the leftover newline
System.out.print("Enter full name: ");
String name = sc.nextLine();
System.out.println(name + " is " + age);
The fix is the bare sc.nextLine() call, which reads and discards the rest of the line. The rule to remember: after any nextInt, nextDouble or next, call nextLine() once before your first real nextLine().
An alternative that avoids the problem entirely is to read everything with nextLine() and convert:
String ageText = sc.nextLine();
int age = Integer.parseInt(ageText.trim());
This is more typing but there is no buffer state to reason about, and trim() removes stray spaces.
Handling bad input
If the user types abc where nextInt() expects a number, Java throws InputMismatchException and the program stops. You can guard against it with sc.hasNextInt(), which reports whether the next token can be read as an integer without actually consuming it.
Reading numbers into a total
A common exam pattern is reading a count and then that many values.
Scanner sc = new Scanner(System.in);
System.out.print("How many subjects? ");
int n = sc.nextInt();
int total = 0;
for (int i = 1; i <= n; i++) {
System.out.print("Marks for subject " + i + ": ");
total += sc.nextInt();
}
System.out.printf("Total: %d, Average: %.2f%n", total, (double) total / n);
Note (double) total / n. Without the cast this would be integer division and the average would lose its decimals.
Common mistakes
- Forgetting
import java.util.Scanner;. The error says the symbol cannot be found. Add the import above the class. - The empty-string
nextLine()afternextInt(). Consume the leftover newline with an extrasc.nextLine(). - Using
next()for a full name. It stops at the first space, soRavi Kumargives youRavi. UsenextLine(). "Total: " + a + bgiving concatenation instead of a sum. Bracket the arithmetic:"Total: " + (a + b).- Mismatching a printf specifier and its argument.
%dwith a double throws at runtime, not at compile time. - Integer division in an average. Cast one operand to
double. - Creating several Scanners on
System.in. Create one, pass it around, and close it once at the end.
With input and formatted output in hand you can write programs that actually interact with someone. Next comes control flow. There are formatting and input exercises on the Practice page.