- Java Comments
- Комментарии на Java: однострочные, многострочные, разница между / * * / и / ** * /
- Виды
- Итог
- Однострочный комментарий в Java
- Пример
- Итог
- Многострочный комментарий в Java
- Пример
- Итог
- Разница между / * * / и / ** * / комментариями в Java
- Пример с / * * /
- Итог с / * * /
- Пример с / ** * /
- Итог с / ** * /
- Комментарии в Java: не всё так просто
- Комментарии Java кода
- Комментарии для документирования
- Заключение
Java Comments
Learn everything about Java comments, types of Java comments, Javadoc tool, the performance impact of comments and best practices to follow.
1. Why should we write comments?
The comments, as the name suggests, are notes we write between the programs for various reasons. For example, you may write comments to –
- Write information or explanation about the variable, method, class or any statement.
- Write text to be available in Java docs.
- Hide program code for a specific time, etc.
Given code is an example of Java comments, and how to use them.
/** * Contains method to greet users by their name and location. * * @author Lokesh Gupta */ public class Main < /** * Launches the application * * @param args - Application startup arguments */ public static void main(String[] args) < getMessage("Lokesh", "India"); >/** * Returns welcome message for a customer by customer name and location * * @param name - Name of the visitor * @param region - Location * @return - Welcome message */ public static String getMessage (String name, String region) < StringBuilder builder = new StringBuilder(); builder.append("Hello "); builder.append(name); builder.append(", Welcome to "); builder.append(region); builder.append(" !!"); return builder.toString(); >>
There are 3 types of comments in Java.
Use single-line comments when the comment can be written in a single line only. These comments are written over Java statements to clarify what they are doing.
//Initialize the counter variable to 0 int counter = 0;
Use multi-line comments when you need to add information in source code that exceeds more than one line. Multi-line comments are used mostly above code blocks with complex logic that cannot be written in a single line.
/* * This function returns a variable which shall be used as a counter for any loop. * Counter variable is of integer type and should not be reset during execution. */ public int getCounter() < // >
The documentation comments are used when you want to expose information to be picked up by the javadoc tool for creating the HTML documentation for classes by reading the source code. This is the information you see in editors (e.g. eclipse) when using autocomplete feature. These comments are pit above classes, interfaces and method definitions.
- Documentation comments start with /** and end with */ . By convention, each line of a doc comment begins with a * , as shown in the following example, but this is optional. Any leading spacing and the * on each line are ignored.
- Within the doc comment, lines beginning with @ are interpreted as special instructions for the documentation generator, giving it information about the source code.
- You can use javadoc annotations inside these comments e.g. @param and @return .
/** * This function returns a variable which shall be used as a counter for any loop. * Counter variable is of integer type and should not be reset during execution. * * @param seed - initial value of the counter * @return counter value */ public int getCounter(int seed) < // >
Doc comments can appear above class, method, and variable definitions, but some tags may not apply to all of these. For example, the @exception tag can only be applied to methods.
Tag | Description | Applies to |
---|---|---|
@see | Associated class name | Class, method, or variable |
@code | Source code content | Class, method, or variable |
@link | Associated URL | Class, method, or variable |
@author | Authjor name | Class |
@version | Version number | Class |
@param | Parameter name and description | Method |
@return | Return type and description | Method |
@exception | Exception name and description | Method |
@deprecated | Declares an item to be obsolete | Class, method, or variable |
@since | Notes API version when item was added | Variable |
Documentation comments are an integral part of programming and should not be skipped.
In Eclipse IDE, simply typing “/** [Enter]” before a public method or class will automatically generate in all necessary @param , @author and @return attributes.
javadoc utility is bundled with JDK distributions. It converts them into standardized, nicely formatted, easy-to-read web pages. It generates API documentation from documentation comments.
4.1. Run javadoc from the command prompt
First, make sure javadoc the utility is in your PATH. If not then add JDK/bin folder to PATH variable.
To generate Java docs, execute the utility with two arguments. First is location of generated Java docs, and second is Java source files. In our case, I executed this command from location where Main.java is.
It generated these Java docs HTML files.
4.2. Run javadoc from Eclipse
You can generate the Java documentation from Eclipse IDE as well. Follow these simple steps-
- In the Package Explorer, right-click the desired project/package.
- Select Export. /Javadoc and click Next .
- You may select “ Private ” for the visibility level to be generated. This will generate all possible Javadocs, even for private methods.
- Select the “ standard doclet ” which is the destination folder for your documentation.
- Click Next .
- Enter a meaningful Document title and click Finish .
If you follow all above steps correctly, you will have generated Java docs file similar to what we saw in command prompt option.
5. Performance Impact of Java Comments
Implementation comments in Java code are only there for humans to read. The Java comments are statements that are not compiled by the compiler, so they are not included into compiled bytecode ( .class file).
And that’s why Java comments have no impact on application performance as well.
6. Java Comments Best Practices
Follow these best practices to have proper comments in your application sourcecode.
- Do not use unnecessary comments in sourcecode. If your code needs more than normal explanation, then possibly re-factor your code.
- Keep comments indentation uniform and match for best readability.
- Comments are for humans so use simple language to explain.
- Always add documentation comments in your sourcecode.
Комментарии на Java: однострочные, многострочные, разница между / * * / и / ** * /
Комментарии на любом языке программирования помогают сделать исходный код читаемым, компилятор игнорирует эти комментарии.
Виды
Java поддерживает три типа комментариев –
- Однострочные комментарии – С их помощью вы можете прокомментировать отдельные строки. Компилятор игнорирует все от // до конца строки.
- Многострочные комментарии – Можете прокомментировать несколько строк. Компилятор игнорирует все от / * до * /.
- Документационные комментарии – Инструмент Javadoc JDK использует этот вид при подготовке автоматически сгенерированной документации.
Следующий пример демонстрирует использование всех трех типов комментариев в Java.
/** * @author Tutorialspoint */ public class CommentsExample < /* Following is the main method here, We create a variable named num. And, print its value * */ public static void main(String args[]) < // Declaring a variable named num int num = 1; // Printing the value of the variable num System.out.println("value if the variable num: "+num); >>
Итог
value if the variable num: 1
Однострочный комментарий в Java
Чтобы прокомментировать конкретную строку, просто поместите двойную косую черту (//) перед строкой, как показано ниже.
// Hello this line is commented
Пример
Следующий пример демонстрирует использование однострочных комментариев в Java –
public class CommentsExample < public static void main(String args[]) < //Declaring a variable named num int num = 1; //Printing the value of the variable num System.out.println("value if the variable num: "+num); >>
Итог
value if the variable num: 1
Многострочный комментарий в Java
Многострочные комментарии в Java начинаются с / * и заканчиваются * /. Вы можете комментировать несколько строк, просто поместив их между / * и * /.
/* Hello this is the way to write multi line comments in Java */
Пример
public class CommentsExample < /* Following is the main method here, We create a variable named num. And, print its value * */ public static void main(String args[]) < int num = 1; System.out.println("value if the variable num: "+num); >>
Итог
value if the variable num: 1
Разница между / * * / и / ** * / комментариями в Java
Чтобы разобраться в разнице между / * * / и / ** * / комментариями в Java приведем примеры.
Многострочные комментарии (/ * * /) используются для комментариев в несколько строк в исходном коде.
Пример с / * * /
public class CommentsExample < /* Following is the main method here, We create a variable named num. And, print its value * */ public static void main(String args[]) < //Declaring a variable named num int num = 1; //Printing the value of the variable num System.out.println("value if the variable num: "+num); >>
Итог с / * * /
value if the variable num: 1
Документационный комментарий (/ ** * /) используется для создания документации по исходному коду с помощью инструмента Javadoc.
Пример с / ** * /
/** * @author Tutorialspoint */ public class CommentsExample < public static void main(String args[]) < int num = 1; System.out.println("value if the variable num: "+num); >>
Итог с / ** * /
value if the variable num: 1
Вы можете сгенерировать Java документацию выше класса с помощью команды Javadoc, как –
C:\Sample>javadoc CommentsExample.java
Средняя оценка 4.4 / 5. Количество голосов: 7
Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.
Видим, что вы не нашли ответ на свой вопрос.
Напишите комментарий, что можно добавить к статье, какой информации не хватает.
Комментарии в Java: не всё так просто
Комментарии — казалось бы, что может быть проще, и чего тут целую статью писать. Но тут не всё так просто. Как говорил мой начальник, код писать может каждый, а вот хороший комментарий написать сложно. Большинство курсов по изучению языка начинаются с традиционного Hello World. Даже в Oracle Tutorials в разделе «Getting Started» мы начинаем с The «Hello World!» Application. И с самых первых строк кода мы видим их — Java комментарии. Их важность также подчёркивается тем, что в таком важном документе, как «Java Code Convention» комментариям отводится отдельный раздел: Comments. Как гласит документация, комментарии в Java делятся на два типа:
- комментарий реализации (или комментарий кода);
- документирующий комментарий.
Комментарии кода используются для описания отдельных строк/блоков, а комментарии для документирования используются, чтобы описать спецификацию кода (его интерфейс), не зависящую от его реализации. Java комментарии игнорируются компилятором, т.к. они несут смысл для разработчика, а не для пользователя. Поэтому можно уменьшить размер компилируемых классов.
Комментарии Java кода
// Строчный комментарий System.out.println("Hello, World!");
/* * Блочный комментарий */ System.out.println("Hello");
Понятно, что нет абсолютной истины, и иногда комментарии необходимы. Но всегда есть варианты, и с излишними комментариями нужно бороться. В этой же главе упоминаются необычные комментарии, TODO:
// TODO: Добавить World System.out.println("Hello, ");
Смысл в них в том, что они могут особым образом обрабатываться в IDE. Например, в IDEA они собираются на отдельной вкладке, где их можно посмотреть:
И небольшой puzzler с комментарием: Строка «http://google.com» является корректной строчкой внутри метода, т.к. http здесь — это на самом деле метка, а дальше — комментарий. Зачастую многие комментарии могут стать из комментариев кода комментарием для документирования, о которых поговорим далее.
Комментарии для документирования
Комментарии для документации описывают общедоступный API. API — это програмный интерфейс приложения, то есть те классы и методы, которые доступны другим разработчикам для выполнения каких-либо действий. Если кратко, то данные комментарии должны пояснять, зачем создан тот или иной класс и пакет и что делает тот или иной метод. Так же можно при необходимости описывать поля класса. Именно то, что оформлено в качестве JavaDoc мы и видим в подсказках наших IDE. Например:
То, как правильно оформлять JavaDoc опять же смотрим в Java Code Convention: Code Convention. Они чем-то похожи на блочные комментарии, но вместо одного астериска (не Астерикса)) используется два. Пример JavaDoc был приведён выше. Описывать все возможности нет смысла, так как об этом уже написано в официальной документации Oracle. Поэтому всё необходимое смотрим в официальной документации по JavaDoc, раздел «Tag Descriptions». У Oracle есть даже отдельный tutorial на эту тему: How to Write Doc Comments for the Javadoc Tool. Подсказки в IDE — хорошо, но на самом деле они не просто так doc. На основе этих JavaDoc комментариев генерируется документация. Для этого есть специальная утилита javadoc. Как мы видим, в том Tutorial об этом и говорится. Описание того, как ей пользоваться, есть на официальном сайте Oracle для JavaDoc. Чтобы увидеть воочию, как это выглядит, можно создать в каталоге подкаталог с названием пакета, например: test. В нём создать простенький класс с комментариями. Например:
package test; /** * This is a JavaDoc class comment */ public class JavaDocTest < /** * This is a JavaDoc public field comment */ public static final String HELLO_MESSAGE = "Hello, World!"; public static void main(String. args) < JavaDocTest.greetings(); >/** * This is a JavaDoc public method comment */ public static void greetings() < System.out.println(HELLO_MESSAGE); >>
После этого можно выполнить следующую команду из каталога, который содержит наш каталог с пакетом: javadoc -d ./test test После этого мы увидим процесс генерации документации.
И после можем открыть index.html, чтобы увидеть сгенерированный документ. Вы часто сможете увидеть, когда выставляют документацию по API. Например, Spring Framework API.
Заключение
Как мы видим, казалось бы, такая простая штука как комментарии на деле оказывается куда сложнее. Поэтому, если комментариям выделить некоторое время и за ними следить, ваш код будет лучше и вы как программист будете ценнее. #Viacheslav