JavaBasic syntax and simple programsCode style

Comments

7 seconds read

Inside a Java program, you can write special text which will be ignored by the java compiler — known as comments. They allow you to exclude code from the compilation process (disable it) or clarify a piece of code to yourself or other developers.

The Java programming language supports three kinds of comments.

End-of-line comments

The java compiler ignores any text from // to the end of the line.

class Program {
    public static void main(String[] args) {
        // The line below will be ignored
        // System.out.println("Hello, World");
        // It prints the string "Hello, Java"
        System.out.println("Hello, Java"); // Here can be any comment
    }
}

In the example above the text after // is ignored by the compiler.

Multi-line comments

The compiler ignores any text from /* and the nearest */. It can be used as multiple and single-line comments.

class Program {
    public static void main(String[] args) {
        /* This is a single-line comment */
        /*  This is a example of
            a multi-line comment */
  }
}

You can use comments inside other comments:

class Program {
    public static void main(String[] args) {
        /*
        System.out.println("Hello"); // print "Hello"
        System.out.println("Java");  // print "Java"
        */
    }
}

The part of code above is ignored by the compiler because of /* ... */ comments.

Java documentation comments

The compiler ignores any text from /** to */ just like it ignores multi-line comments.

This kind of comments can be used to automatically generate documentation about your source code using the javadoc tool. Usually, these comments are placed above declarations of classes, interfaces, methods and so on. Also, in this case, some special labels such as @param, @return and others are used for controlling the tool.

See an example below.

class Program {
    /**
     * The main method accepts an array of string arguments
     *
     * @param args from the command line
     */
    public static void main(String[] args) {
        // do nothing
    }
}

Do not be afraid if you have not understood the documentation comments completely. This will be considered in separated topics.

Note, in this course we use comments in the theory and practice lessons to explain how and why our code works.

12 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo