Java System exit() 方法



描述

java System exit() 方法終止當前正在執行的 Java 虛擬機器。

引數用作狀態程式碼;按照慣例,非零狀態程式碼表示異常終止。

宣告

以下是java.lang.System.exit() 方法的宣告

public static void exit(int status)

引數

status - 這是退出狀態。

返回值

此方法不返回值。

異常

SecurityException - 如果存在安全管理器並且其 checkExit 方法不允許以指定狀態退出。

示例:根據條件終止程式

以下示例顯示了 Java System exit() 方法的用法。在此程式中,我們建立了兩個 int 型別的陣列,並用一些值初始化它們。現在使用 System.arraycopy() 方法,將第一個陣列 arr1 的第一個元素複製到第二個陣列的索引 0 處。然後我們列印第二個陣列以顯示更新後的陣列作為結果。在下一個 for 迴圈語句中,我們在檢查陣列元素值是否大於 20 時使用了 exit() 語句。因此,只打印了 array2 的三個元素,程式退出。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) {

      int arr1[] = { 0, 1, 2, 3, 4, 5 };
      int arr2[] = { 0, 10, 20, 30, 40, 50 };
      int i;
      
      // copies an array from the specified source array
      System.arraycopy(arr1, 0, arr2, 0, 1);
      System.out.print("array2 = ");
      for(int i= 0; i < arr2.length; i++) {
    	  System.out.print(arr2[i] + " ");
      }
      
      for(i = 0;i < 3;i++) {
         if(arr2[i] > = 20) {
            System.out.println("exit...");
            System.exit(0);
         } else {
            System.out.println("arr2["+i+"] = " + arr2[i]);
         }
      }
   }
} 

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

array2 = 0 10 20 30 40 50 60
arr2[0] = 0
arr2[1] = 10
exit...
java_lang_system.htm
廣告