Java Comments
A comment is text in your program that Java ignores. Comments are written for people: for the next person who reads your code, and for yourself a month from now. Good comments explain why the code does something, because the code itself already shows what it does.
Single-line comments
Two slashes // start a comment that runs to the end of the line. It can be on a line of its own or after a statement:
public class Main {
public static void main(String[] args) {
// Greet the user
System.out.println("Welcome!");
System.out.println("Goodbye!"); // printed last
}
}Welcome! Goodbye!
Multi-line comments
A comment between /* and */ can cover several lines:
public class Main {
public static void main(String[] args) {
/*
* This program prints the sum of two numbers.
* Written while learning Java.
*/
System.out.println(15 + 27);
}
}42
The stars at the start of the middle lines are only decoration; Java ignores everything between /* and */.
Switching code off
Comments are also useful while you test. Put // in front of a line and Java skips it, without you having to delete it:
public class Main {
public static void main(String[] args) {
System.out.println("Line one");
// System.out.println("Line two");
System.out.println("Line three");
}
}Line one Line three
Only lines one and three are printed. Remove the // and the middle line comes back.
Documentation comments
A comment that starts with /** is a documentation comment (Javadoc). Java's own documentation is written this way: a tool reads these comments and builds web pages from them. You put one just before a class or a method that you will write in later topics, such as Methods:
/**
* Returns the larger of two numbers.
* @param a the first number
* @param b the second number
*/For now, // comments are all you need.
Tips for good comments
- Do not repeat the code:
x = x + 1; // add one to xtells the reader nothing new. - Explain decisions:
// prices are in paise so that sums stay exact. - Keep comments up to date when you change the code. A wrong comment is worse than none.
Practice exercises
- Add a comment above each
printlnof one of your earlier programs, saying what it prints. - Write a multi-line comment at the top of a program with your name and the date.
- Comment out one line of a program, run it, then bring the line back.