Java 中返回类型的含义?


一个 return 语句 会导致程序控制权返回到方法的调用者。每一个 Java 方法 都声明了一个返回类型,而对所有 Java 方法而言这是必须的。返回类型可以是 基本类型,如 int、float、double,引用类型 或 void 类型(不返回任何内容)。

关于返回值有几个重要的内容需要了解。

  • 方法返回的数据类型必须与方法指定的返回类型兼容。例如,如果某个方法的返回类型为 boolean,那么就不能返回一个整数。

  • 接收方法返回值的变量也必须与为该方法指定的返回类型兼容。

  • 可以在一个序列中传递参数,方法必须按同一序列接受它们。

示例 1

Open Compiler
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

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

示例 2

Open Compiler
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+ 浏览

开启您的 职业

完成课程获得认证

开始
广告