Thursday 13 July 2017

Java Comments in java ~ foundjava

The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.
  1. Single Line Comment
  2. Multi Line Comment
  3. Documentation Comment

1) Java Single Line Comment

The single line comment is used to comment only one line.
Syntax:
  1. //This is single line comment  
Example:
  1. public class CommentExample1 {  
  2. public static void main(String[] args) {  
  3.     int i=10;//Here, i is a variable  
  4.     System.out.println(i);  
  5. }  
  6. }  
Output:
10

2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.
Syntax:
  1. /* 
  2. This  
  3. is  
  4. multi line  
  5. comment 
  6. */  
Example:
  1. public class CommentExample2 {  
  2. public static void main(String[] args) {  
  3. /* Let's declare and 
  4.  print variable in java. */  
  5.     int i=10;  
  6.     System.out.println(i);  
  7. }  
  8. }  
Output:
10

3) Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API, you need to use javadoc tool.
Syntax:
  1. /** 
  2. This  
  3. is  
  4. documentation  
  5. comment 
  6. */  
Example:
  1. /** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/  
  2. public class Calculator {  
  3. /** The add() method returns addition of given numbers.*/  
  4. public static int add(int a, int b){return a+b;}  
  5. /** The sub() method returns subtraction of given numbers.*/  
  6. public static int sub(int a, int b){return a-b;}  
  7. }  
Compile it by javac tool:
javac Calculator.java
Create Documentation API by javadoc tool:
javadoc Calculator.java
Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML files and see the explanation of Calculator class provided through documentation comment.

No comments:

Post a Comment