Java 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)
定義和用法
return
關鍵字用於結束方法的執行,並可用於從方法中返回值。
更多示例
提示:使用 void
關鍵字來指定方法不應有返回值
示例
一個沒有返回值的方法
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
相關頁面
在我們的 Java 方法教程 中閱讀更多關於方法的資訊。