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 方法教程 中阅读更多关于方法的信息。