Java Output
Java output is the text and numbers a program prints to the screen. The println method prints a value and then ends the line.
println ends the line
Each println call ends its own line. The two calls print two lines.
public class Main {
public static void main(String[] args) {
System.out.println("Hello");
System.out.println("World");
}
}print stays on the line
Neither print call ends the line. The two calls share one output line.
public class Main {
public static void main(String[] args) {
System.out.print("Hello");
System.out.print(" World");
}
}Numbers print without quotes
A whole number and a decimal number print as numbers. No quotes appear in the output.
public class Main {
public static void main(String[] args) {
System.out.println(42);
System.out.println(3.5);
}
}Maths inside println
The expression 3 + 4 is worked out before printing. The result 7 prints.
public class Main {
public static void main(String[] args) {
System.out.println(3 + 4);
}
}Example
public class Main {
public static void main(String[] args) {
System.out.println("Receipt");
System.out.println("Pen: 3 dollars");
System.out.println("Book: 5 dollars");
System.out.print("Total: ");
System.out.println(3 + 5);
}
}Key points
- println prints a value and ends the line.
- print prints a value and stays on the same line.
- Text prints inside double quotes.
- Numbers print without quotes.
- A maths expression inside println prints its result.
- System.out is the output stream of the program.
In this example, the first three lines print a receipt heading and two items. The print call writes the Total label and stays on the line. The last println call adds 3 and 5 and prints 8 beside the label.
Note
println and print are both reached through System.out.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does println do after it prints a value?