Java Comments

Java provides the ability to put comments into your source code. There are three types of comments: multiline, single line, and Javadoc. All three types of comments are ignored by the compiler. I'll save the Javadoc comments for a later tutorial, so for now I'll just stick with teaching you multiline and single line comments. This simple tutorial will explain the proper way to use both.



Multiline comment
/*
    Multiline comments are nested inside a forward slash and an asterisk,
    the comment is closed out with another asterisk and a forward slash.
*/
Single line comment
// A single line comment trails a pair of forward slashes.

Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md Comments
C:\Java>cd Comments
C:\Java\Comments>Notepad Comments.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


/*
	The compiler ignores comments so you can place them almost anywhere.
	This multiline comment is above the class declartion
*/
// A simple single line comment
class Comments {
	// The main method
	public static void main(String args[]) {
		/* 
			System.out.println("This will not display");
			System.out.println("Neither will this");
		*/
		System.out.pr/* comment */intln("Will this work?");
		System.out.println("Do not nest comments inside of an expression statement");
		// No it won't
	}
}

Now switch back to the command prompt (CMD) and type in javac Comments.java and press Enter.
You will receive a compiler error on the Will this work? line.
Go back to notepad and type // in front of that line of code to comment it out.
Now switch back to the command prompt (CMD) and type in javac Comments.java and press Enter.
Now type in java Comments and press Enter.


C:\Java\Comments>javac Comments.java
C:\Java\Comments>java Comments
Do not nest comments inside of a expression statement


Final thoughts

Comments are useful and can be placed almost anywhere inside of a Java source code file.


Tutorials