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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便