Java 中使用 final 變數時無法觸發的語句
無法觸發的語句是指在程式碼執行時無法執行的語句。這可能是因為 −
- 程式碼之前有 return 語句。
- 程式碼中有一個無限迴圈。
- 程式碼的執行在執行前被強行終止。
這裡,我們將看到如何將無法觸發的語句與 ‘final’ 關鍵字一起使用 −
示例
class Demo_example{
final int a = 56, b = 99;
void func_sample(){
while (a < b){
System.out.println("The first value is less than the second.");
}
System.out.println("This is an unreachable statement");
}
}
public class Demo{
public static void main(String args[]){
Demo_example my_instance = new Demo_example();
my_instance.func_sample();
}
}輸出
/Demo.java:11: error: unreachable statement
System.out.println("This is an unreachable statement");
^
1 error一個名為 ‘Demo_example’ 的類包含兩個 final 整數(基本上就像常量),以及一個名為 ‘func_sample’ 的函式,用於比較這兩個整數。在控制檯中顯示相關訊息。定義了另一個名為 ‘Demo’ 的類,並且它包含 main 函式。在此函式中,建立了 Demo 類的例項,並且在此例項上呼叫函式 ‘func_sample’。在控制檯中顯示相關輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP