Java Output
Java sends output to the console with System.out, using println to add a new line and print to stay on the same line.
Printing to the console
The most common way to show output in Java is System.out.println, which prints a value and then moves to a new line. It is the tool you will reach for constantly while learning, both to display results and to check what your program is doing.
Printing lines
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.println("Each println starts a new line.");
}
}println versus print
System.out.print works just like println but does not add a new line at the end, so the next output continues on the same line. Use print when you want to build a line piece by piece and println when you want each value on its own line.
Staying on the same line
public class Main {
public static void main(String[] args) {
System.out.print("Hello");
System.out.print(" ");
System.out.println("World");
}
}Printing numbers and expressions
You can print numbers directly, without quotation marks. If you place a math expression inside the print, Java calculates the result first and then prints it. Text must be wrapped in double quotes, but numbers must not be, or they will be treated as text instead of values.
Numbers and calculations
public class Main {
public static void main(String[] args) {
System.out.println(42);
System.out.println(10 + 5);
System.out.println("Total: " + (10 + 5));
}
}Common pitfalls
- Text values must be inside double quotes: "like this"
- Numbers used as values must not be quoted, or they become text
- System, out, and println are case-sensitive and must be spelled exactly
- Each print statement still needs a semicolon at the end
Exercise: Java Output
What is the difference between System.out.println() and System.out.print()?