Java Output and Comments
Java output is how your program shows results, and comments are notes that explain your code. Both are things you will use in every program you write.
println vs print
System.out.println prints text and then moves to a new line. System.out.print prints text without a line break, so the next output continues on the same line.
public class Main {
public static void main(String[] args) {
System.out.print("Hello, ");
System.out.print("world");
System.out.println("!");
System.out.println("New line here.");
System.out.println(7 * 6);
}
}Hello, world! New line here. 42
Formatted Output with printf
printf lets you build output from a template. %s inserts a string, %d an integer, %.2f a decimal with two places, and %n a new line.
public class Main {
public static void main(String[] args) {
String item = "Coffee";
int qty = 3;
double price = 2.5;
System.out.printf("%s x %d = %.2f%n", item, qty, qty * price);
String line = String.format("Total: %8.2f|", 7.5);
System.out.println(line);
}
}Coffee x 3 = 7.50 Total: 7.50|
String.format works like printf but returns the text instead of printing it. %8.2f pads the number to eight characters wide, which is handy for lining up columns.
Java Comments
Comments are ignored by the compiler. Use them to explain why code does something, not to repeat what it obviously does.
/**
* Javadoc comment: describes the class for documentation tools.
*/
public class Main {
public static void main(String[] args) {
// Single-line comment
int speed = 60; // comment at the end of a line
/* Multi-line comment
spanning several lines */
System.out.println("Speed: " + speed);
}
}Speed: 60
Comment Types
- // starts a single-line comment.
- /* ... */ wraps a multi-line comment.
- /** ... */ is a Javadoc comment, used to generate API documentation.
- Commenting out a line is a quick way to disable it while debugging.
Frequently asked questions
What is the difference between print and println in Java?
println adds a line break after the text, while print does not. Use print when you want several outputs on the same line.
How do I print a double with 2 decimal places in Java?
Use System.out.printf("%.2f%n", value) or String.format("%.2f", value). Both round the value to two decimal places.
Do comments slow down a Java program?
No. The compiler removes comments completely, so they have no effect on the compiled bytecode or its speed.