Java注釋

java注釋是不會被編譯器和解釋器執行的語句。 注釋可以用於提供關於變數,方法,類或任何語句的資訊或解釋。 它也可以用於在特定時間隱藏程式代碼。

Java注釋的類型

在Java中有3種類型的注釋。它們分別如下 -

  1. 單行注釋
  2. 多行注釋
  3. 文檔注釋

1)Java單行注釋

單行注釋僅用於注釋一行,它使用的是 // 兩個字元作為一行注釋的開始,如下語法所示 -

語法:

// This is single line comment

示例:

public class CommentExample1 {
    public static void main(String[] args) {
        int i = 10;// Here, i is a variable
        System.out.println(i);
        int j = 20;
        // System.out.println(j); 這是另一行注釋,這行代碼不會被執行。

    }
}

上面示例代碼輸出結果如下 -

10

2)Java多行注釋

多行注釋用於注釋多行代碼。它以 /* 開始,並以 */ 結束,在 /**/之間的代碼塊就是一個注釋塊,其中的代碼是不會這被執行的。

語法:

/*
This
is
multi line
comment
*/

示例:

public class CommentExample2 {
    public static void main(String[] args) {
        /*
         * Let's declare and print variable in java.
         *
         *  這是多行注釋
         */
        int i = 10;
        System.out.println(i);
    }
}

上面示例代碼輸出結果如下 -

10

3)Java文檔注釋

文檔注釋用於創建文檔API。 要創建文檔API,需要使用javadoc工具。

語法:

/**
This
is
documentation
comment
*/

示例:

/**
 * The Calculator class provides methods to get addition and subtraction of
 * given 2 numbers.
 */
public class Calculator {
    /** The add() method returns addition of given numbers. */
    public static int add(int a, int b) {
        return a + b;
    }

    /** The sub() method returns subtraction of given numbers. */
    public static int sub(int a, int b) {
        return a - b;
    }
}

通過javac工具編譯:

javac Calculator.java

通過javadoc工具創建文檔API:

javadoc Calculator.java

現在,將在當前目錄中為上面的Calculator類創建了HTML檔。 打開HTML檔,並查看通過文檔注釋提供的Calculator類的說明。如下所示 -


上一篇: Java continue語句 下一篇: Java基礎實例程式