Commented code in java

Comments in Java

In a program, comments are like indents one makes, they are used so that it is easier for someone who isn’t familiar with the language to be able to understand the code. It will also make the job easier for you, as a coder, to find errors in the code since you will be easily able to find the location of the bug. Comments are ignored by the compiler while compiling a code, which makes the job more complex in the long run when they have to go through so much code to find one line.

In Java there are three types of comments:

A. Single-line comments

A beginner-level programmer uses mostly single-line comments for describing the code functionality. It’s the easiest typed comments.

//Comments here( Text in this line only is considered as comment )

Illustration:

Examples in an actual code

Java

Single line comment above

B. Multi-line Comments:

To describe a full method in a code or a complex snippet single line comments can be tedious to write since we have to give ‘//’ at every line. So to overcome this multi-line comments can be used.

/*Comment starts continues continues . . . Comment ends*/

Java

Multi line comments below

We can also accomplish single line comments by using the above syntax as shown below:

Читайте также:  Executing shell command in php

C. Documentation Comments:

This type of comment is used generally when writing code for a project/software package, since it helps to generate a documentation page for reference, which can be used for getting information about methods present, its parameters, etc. For example, http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html is an auto-generated documentation page that is generated by using documentation comments and a javadoc tool for processing the comments.

/**Comment start * *tags are used in order to specify a parameter *or method or heading *HTML tags can also be used *such as * *comment ends*/

Java

Tag Description Syntax
@author Adds the author of a class. @author name-text
Displays text in code font without interpreting the text as HTML markup or nested javadoc tags.
Represents the relative path to the generated document’s root directory from any generated page.
@deprecated Adds a comment indicating that this API should no longer be used. @deprecated deprecatedtext
@exception Adds a Throws subheading to the generated documentation, with the classname and description text. @exception class-name description
Inherits a comment from the nearest inheritable class or implementable interface. Inherits a comment from the immediate surperclass.
Inserts an in-line link with the visible text label that points to the documentation for the specified package, class, or member name of a referenced class.
Identical to , except the link’s label is displayed in plain text than code font.
@param Adds a parameter with the specified parameter-name followed by the specified description to the “Parameters” section. @param parameter-name description
@return Adds a “Returns” section with the description text. @return description
@see Adds a “See Also” heading with a link or text entry that points to reference. @see reference
@serial Used in the doc comment for a default serializable field. @serial field-description | include | exclude
@serialData Documents the data written by the writeObject( ) or writeExternal( ) methods. @serialData data-description
@serialField Documents an ObjectStreamField component. @serialField field-name field-type field-description
@since Adds a “Since” heading with the specified since-text to the generated documentation. @since release
@throws The @throws and @exception tags are synonyms. @throws class-name description
When is used in the doc comment of a static field, it displays the value of that constant.
@version Adds a “Version” subheading with the specified version-text to the generated docs when the -version option is used. @version version-text

Implementation:

Java

*

Find average of three numbers!

Average of 10, 20 and 30 is :20

For the above code documentation can be generated by using the tool ‘javadoc’:

Javadoc can be used by running the following command in the terminal.

This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

Источник

Commented code in java

The information on this page is for Archive Purposes Only

5 — Comments

Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are those found in C++, which are delimited by /*. */, and //. Documentation comments (known as «doc comments») are Java-only, and are delimited by /**. */. Doc comments can be extracted to HTML files using the javadoc tool.

Implementation comments are meant for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective. to be read by developers who might not necessarily have the source code at hand.

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.

Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves.

Note:The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.

Comments should not be enclosed in large boxes drawn with asterisks or other characters.
Comments should never include special characters such as form-feed and backspace.

5.1 Implementation Comment Formats

Programs can have four styles of implementation comments: block, single-line, trailing, and end-of-line.

5.1.1 Block Comments

Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments may be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they describe.

A block comment should be preceded by a blank line to set it apart from the rest of the code.

/*-* Here is a block comment with some very special * formatting that I want indent(1) to ignore. * * one * two * three */ 

5.1.2 Single-Line Comments

Short comments can appear on a single line indented to the level of the code that follows. If a comment can’t be written in a single line, it should follow the block comment format (see section 5.1.1). A single-line comment should be preceded by a blank line. Here’s an example of a single-line comment in Java code (also see «Documentation Comments» on page 9):

5.1.3 Trailing Comments

Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting.

Here’s an example of a trailing comment in Java code:

5.1.4 End-Of-Line Comments

The // comment delimiter can comment out a complete line or only a partial line. It shouldn’t be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow:

if (foo > 1) else < return false; // Explain why here. >//if (bar > 1) < // // // Do a triple-flip. // . //>//else < // return false; //>

5.2 Documentation Comments

Note: See «Java Source File Example» on page 19 for examples of the comment formats described here.

For further details, see «How to Write Doc Comments for Javadoc» which includes information on the doc comment tags (@return, @param, @see): link

Doc comments describe Java classes, interfaces, constructors, methods, and fields. Each doc comment is set inside the comment delimiters /**. */ , with one comment per class, interface, or member. This comment should appear just before the declaration:

/** * The Example class provides . */ public class Example < . 

Notice that top-level classes and interfaces are not indented, while their members are. The first line of doc comment (/**) for classes and interfaces is not indented; subsequent doc comment lines each have 1 space of indentation (to vertically align the asterisks). Members, including constructors, have 4 spaces for the first doc comment line and 5 spaces thereafter.

If you need to give information about a class, interface, variable, or method that isn't appropriate for documentation, use an implementation block comment (see section 5.1.1) or single-line (see section 5.1.2) comment immediately after the declaration. For example, details about the implementation of a class should go in in such an implementation block comment following the class statement, not in the class doc comment.

Doc comments should not be positioned inside a method or constructor definition block, because Java associates documentation comments with the first declaration after the comment.

Источник

Комментарии в языке Java

Java-университет

Комментарии в языке Java - 1

Комментарии в языке Java — как и в большинстве других языков программирования, символы, которые игнорируются при выполнении программы. Таким образом, в программу можно добавлять столько комментариев, сколько потребуется, не опасаясь увеличить ее объем. Комментарии используются для описания тонкостей работы конкретного блока кода, метода или класса. Также можно использовать их, если хочется оставить сообщения для программистов, которые в будущем будут работать с этим кодом. Ну или же для собственных заметок.

Способы выделения комментариев

Комментарий реализации (комментарий кода)

  1. Комментирование строки Это самый часто используемый тип комментариев. Чтобы написать такой комментарий, нужно использовать две косые черты // . При этом комментарий начинается сразу за символами // и продолжается до конца строки.
 System.out.println("Hello, Java world!"); // наш комментарий 
 /* Пример простой программы на Java */ public class SampleProgram < public static void main (String [] args) < System.out.println("Hello, Java world!"); >> 

Документирующий комментарий

Для документирования методов, переменных или классов используется особый способ выделения текста. Делается это с помощью /** и */ . При этом каждая строка комментируемого текста начинается с * .Если документируется метод, принято описывать его аргументы и возвращаемое значение.

 /** * Метод возвращает максимальное значение * из трех переданных аргументов * @param a - первый параметр * @param b - второй параметр * @param c - третий параметр * @return - максимальный из параметров */ public int max(int a, int b, int c)

Что еще почитать? Например, этот материал: Комментарии в Java: не всё так просто. Или лекцию из квеста Java Syntax Pro о комментариях.

Источник

Оцените статью