Java 中返回型別的含義?


一個 return 語句 會導致程式控制權返回到方法的呼叫者。每一個 Java 方法 都聲明瞭一個返回型別,而對所有 Java 方法而言這是必須的。返回型別可以是 基本型別,如 int、float、double,引用型別 或 void 型別(不返回任何內容)。

關於返回值有幾個重要的內容需要了解。

  • 方法返回的資料型別必須與方法指定的返回型別相容。例如,如果某個方法的返回型別為 boolean,那麼就不能返回一個整數。

  • 接收方法返回值的變數也必須與為該方法指定的返回型別相容。

  • 可以在一個序列中傳遞引數,方法必須按同一序列接受它們。

示例 1

public class ReturnTypeTest1 {
   public int add() { // without arguments
      int x = 30;
      int y = 70;
      int z = x+y;
      return z;
   }
   public static void main(String args[]) {
      ReturnTypeTest1 test = new ReturnTypeTest1();
      int add = test.add();
      System.out.println("The sum of x and y is: " + add);
   }
}

輸出

The sum of x and y is: 100

示例 2

public class ReturnTypeTest2 {
   public int add(int x, int y) { // with arguments
      int z = x+y;
      return z;
   }
   public static void main(String args[]) {
      ReturnTypeTest2 test = new ReturnTypeTest2();
      int add = test.add(10, 20);
      System.out.println("The sum of x and y is: " + add);
   }
}

輸出

The sum of x and y is: 30

更新於:2023 年 11 月 23 日

25K+ 瀏覽

開啟您的 職業

完成課程獲得認證

開始
廣告