Shiklo Programming
EN
  • English
  • Español
  • Português
  • Deutsch
  • Français
  • 日本語
  • हिन्दी

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
    }
}
Output
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);
    }
}
Output
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");
    }
}
Output
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 x tells 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

  1. Add a comment above each println of one of your earlier programs, saying what it prints.
  2. Write a multi-line comment at the top of a program with your name and the date.
  3. Comment out one line of a program, run it, then bring the line back.