Java Output
A program that does not show anything is not very useful. In Java you print to the terminal with System.out, which has three methods you will use all the time: println, print and printf.
println and print
println prints its text and then moves to a new line. print prints its text and stays on the same line, so the next output continues right after it:
public class Main {
public static void main(String[] args) {
System.out.println("First line");
System.out.print("Same ");
System.out.print("line ");
System.out.println("here.");
System.out.println("Last line");
}
}First line Same line here. Last line
An empty System.out.println(); prints just a new line, which is a simple way to leave an empty line in the output.
Printing numbers and calculations
Numbers are written without quotes. If you print a calculation, Java works it out first and prints the result:
public class Main {
public static void main(String[] args) {
System.out.println(42);
System.out.println(7 + 3);
System.out.println(10 * 4);
System.out.println("7 + 3");
}
}42 10 40 7 + 3
Look at the last line: with quotes, "7 + 3" is just text, so Java prints it as it is.
Special characters
Inside quotes, a backslash starts an escape sequence, a way to write characters you cannot type directly:
| Sequence | Meaning |
|---|---|
\n | new line |
\t | tab (jump to the next column) |
\" | a double quote inside the text |
\\ | one backslash |
public class Main {
public static void main(String[] args) {
System.out.println("Name\tAge");
System.out.println("Asha\t21");
System.out.println("She said \"hello\".\nNew line here.");
}
}Name Age Asha 21 She said "hello". New line here.
printf: formatted output
printf prints text with placeholders that are filled with values: %d for a whole number, %s for text, %.2f for a decimal number with two digits after the point, and %n for a new line.
public class Main {
public static void main(String[] args) {
System.out.printf("%s is %d years old.%n", "Ravi", 30);
System.out.printf("Price: %.2f%n", 19.5);
}
}Ravi is 30 years old. Price: 19.50
The String Formatting topic shows many more placeholders. For now, println is all you need, and printf is handy when numbers must look neat.
Practice exercises
- Print your name, then on the same line your age, using one
printand oneprintln. - Print a small table with three rows of a name and a score, separated by
\t. - Use
printfto print the result of22.0 / 7with three digits after the point.