Java中返回类型的重要性?

一个return语句 导致程序的控制转移回方法的调用者。Java中的每个方法都用返回类型声明,并且对于所有Java方法都是必需的。返回类型可以是原语类型像我NT,浮点,双精度,一个引用类型空隙 (返回任何)。

关于返回值,需要了解一些重要事项

  • 方法返回的数据类型必须与方法指定的返回类型兼容。例如,如果某些方法的返回类型为布尔值,则无法返回整数。

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

  • 这些参数可以按顺序传递,并且必须由该方法按相同顺序接受。

例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