首頁  >  文章  >  Java  >  Java 9中的try-with-resources中的有效final變數?

Java 9中的try-with-resources中的有效final變數?

PHPz
PHPz轉載
2023-09-20 08:25:021368瀏覽

Java 9中的try-with-resources中的有效final变量?

Try with Resource 語句中使用的任何變數都需要在Try 語句中聲明,直到Java 8 版本。從Java 9開始,此限制已被刪除,並且任何final 有效final變數已在嘗試封鎖。 Effectively Final 表示變數一旦初始化就無法改變。

範例

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class EffectivelyFinalTest {
   private static File file = new File("try_resources.txt");
      public static void main(String args[]) throws IOException {
      file.createNewFile();
      BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

      <strong>try</strong>(<strong>bufferedReader</strong>) {
         System.out.println("Can Use Final or Effectively Final in Try with Resources!");
      } finally {
         System.out.println("In finally block");
      }
}
}

輸出

<strong>Can Use Final or Effectively Final in Try with Resources!
In finally block</strong>

以上是Java 9中的try-with-resources中的有效final變數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除