Java Comments
In this page:
Single-Line Comments
A // comment runs from that point to the end of the line, making it ideal for short, one-line notes explaining a tricky piece of logic right next to the code it describes.
Example: Single-Line Comments
public class Main {
public static void main(String[] args) {
int total = 100; // running total for the cart
System.out.println(total);
}
}
Login to try C/C++/Java/PHP code in the editor
Multi-Line Comments
A /* ... */ block comment can span multiple lines, which is useful for temporarily disabling a chunk of code or writing a longer explanation above a complex method.
Example: Multi-Line Comments
public class Main {
/*
* This block comment can span
* multiple lines of explanation.
*/
public static void main(String[] args) {
System.out.println("See the block comment above.");
}
}
Login to try C/C++/Java/PHP code in the editor
Javadoc Comments
Javadoc comments (/** ... */) placed above a class or method get picked up by the javadoc tool to auto-generate browsable HTML API documentation -- this is how Java's own standard library docs are built.
Example: Javadoc Comments
public class Main {
/**
* Adds two integers together.
* @param a first number
* @param b second number
* @return the sum of a and b
*/
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3));
}
}
Login to try C/C++/Java/PHP code in the editor
Commenting Out Code
Wrapping code in // or /* */ during debugging lets you quickly rule out whether a specific block is causing a bug, without deleting and having to retype it afterward.
Example: Commenting Out Code
public class Main {
public static void main(String[] args) {
System.out.println("Active line");
// System.out.println("Disabled while debugging");
}
}
Login to try C/C++/Java/PHP code in the editor
Comment Best Practices
Stale comments that no longer match the code they describe are worse than no comment at all, since they actively mislead the next reader -- update or delete them whenever you change the logic nearby.
Example: Comment Best Practices
public class Main {
public static void main(String[] args) {
int price = 20; // price in dollars (kept in sync with the code beside it)
System.out.println(price);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: