Комментарии в Java

Опубликовано: 15 Февраля, 2022


В программе комментарии участвуют в том, чтобы сделать программу более удобочитаемой для человека за счет размещения деталей задействованного кода, а правильное использование комментариев упрощает обслуживание и поиск ошибок. Комментарии игнорируются компилятором при компиляции кода.

В Java есть три типа комментариев:

  1. Однострочные комментарии.
  2. Многострочные комментарии.
  3. Комментарии к документации.

Однострочные комментарии

Программист начального уровня использует в основном однострочные комментарии для описания функциональности кода. Это самые простые напечатанные комментарии.
Синтаксис:

// Комментарии здесь (текст только в этой строке считается комментарием)

Пример:

Многострочные комментарии

Чтобы описать полный метод в коде или сложный фрагмент однострочного комментария, может быть утомительно писать, поскольку мы должны ставить «//» в каждой строке. Таким образом, чтобы преодолеть этот многострочный комментарий, можно использовать.
Синтаксис:

/ * Комментарий начинается
продолжается
продолжается
.
.
.
Прием заканчивается * /

Example:

//Java program to show multi line comments
class Scomment
{
    public static void main(String args[])
    
        System.out.println("Multi line comments below");
        /*Comment line 1
          Comment line 2 
          Comment line 3*/
    }
}

Мы также можем выполнять однострочные комментарии, используя приведенный выше синтаксис, как показано ниже:

/ * Строка комментария 1 * /

Документация Комментарии

Этот тип комментариев обычно используется при написании кода для проекта / программного пакета, поскольку он помогает создать страницу документации для справки, которую можно использовать для получения информации о существующих методах, их параметрах и т. Д.
Например, http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html - это автоматически сгенерированная страница документации, которая создается с использованием комментариев документации и инструмента javadoc для обработки комментариев.

Синтаксис:

/ ** Начало комментария
*
* теги используются для указания параметра
* или метод, или заголовок
* Также можно использовать HTML-теги 
* например, <h1>
*
* комментарий заканчивается * /

Available tags to use:

TagDescriptionSyntax
@authorAdds the author of a class.@author name-text
{@code}Displays text in code font without interpreting the text as HTML markup or nested javadoc tags.{@code text}
{@docRoot}Represents the relative path to the generated document’s root directory from any generated page.{@docRoot}
@deprecatedAdds a comment indicating that this API should no longer be used.@deprecated deprecatedtext
@exceptionAdds a Throws subheading to the generated documentation, with the classname and description text.@exception class-name description
{@inheritDoc}Inherits a comment from the nearest inheritable class or implementable interface.Inherits a comment from the immediate surperclass.
{@link}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.{@link package.class#member label}
{@linkplain}Identical to {@link}, except the link’s label is displayed in plain text than code font.{@linkplain package.class#member label}
@paramAdds a parameter with the specified parameter-name followed by the specified description to the “Parameters” section.@param parameter-name description
@returnAdds a “Returns” section with the description text.@return description
@seeAdds a “See Also” heading with a link or text entry that points to reference.@see reference
@serialUsed in the doc comment for a default serializable field.@serial field-description | include | exclude
@serialDataDocuments the data written by the writeObject( ) or writeExternal( ) methods.@serialData data-description
@serialFieldDocuments an ObjectStreamField component.@serialField field-name field-type field-description
@sinceAdds a “Since” heading with the specified since-text to the generated documentation.@since release
@throwsThe @throws and @exception tags are synonyms.@throws class-name description
{@value}When {@value} is used in the doc comment of a static field, it displays the value of that constant.{@value package.class#field}
@versionAdds a “Version” subheading with the specified version-text to the generated docs when the -version option is used.@version version-text
//Java program to illustrate frequently used 
// Comment tags
  
/**
* <h1>Find average of three numbers!</h1>
* The FindAvg program implements an application that
* simply calculates average of three integers and Prints
* the output on the screen.
*
* @author  Pratik Agarwal
* @version 1.0
* @since   2017-02-18
*/
public class FindAvg 
{
    /**
    * This method is used to find average of three integers.
    * @param numA This is the first parameter to findAvg method
    * @param numB  This is the second parameter to findAvg method
    * @param numC  This is the second parameter to findAvg method
    * @return int This returns average of numA, numB and numC.
    */
    public int findAvg(int numA, int numB, int numC) 
    {
        return (numA + numB + numC)/3;
    }
  
    /**
    * This is the main method which makes use of findAvg method.
    * @param args Unused.
    * @return Nothing.
    */
  
    public static void main(String args[]) 
    {
        FindAvg obj = new FindAvg();
        int avg = obj.findAvg(10, 20, 30);
  
        System.out.println("Average of 10, 20 and 30 is :" + avg);
    }
}

Выход:

Среднее значение 10, 20 и 30 составляет: 20

Для приведенного выше кода документацию можно создать с помощью инструмента javadoc:
Javadoc можно использовать, выполнив следующую команду в терминале.

javadoc FindAvg.java

Эта статья предоставлена Pratik Agarwal . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью с помощью provide.geeksforgeeks.org или отправить ее по электронной почте на deposit@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.

Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .