Java 返回
返回值
在上一頁,我們在所有示例中都使用了 void
關鍵字,這表示該方法不應返回值。
如果您希望方法返回一個值,可以使用基本資料型別(如 int
、char
等)代替 void
,並在方法中使用 return
關鍵字
示例
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)
此示例返回方法中 **兩個引數** 的總和
示例
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
System.out.println(myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)
您還可以將結果儲存在變數中(推薦,因為它更易於閱讀和維護)
示例
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int z = myMethod(5, 3);
System.out.println(z);
}
}
// Outputs 8 (5 + 3)