Java 中返回类型的含义?
一个 return 语句 会导致程序控制权返回到方法的调用者。每一个 Java 方法 都声明了一个返回类型,而对所有 Java 方法而言这是必须的。返回类型可以是 基本类型,如 int、float、double,引用类型 或 void 类型(不返回任何内容)。
关于返回值有几个重要的内容需要了解。
方法返回的数据类型必须与方法指定的返回类型兼容。例如,如果某个方法的返回类型为 boolean,那么就不能返回一个整数。
接收方法返回值的变量也必须与为该方法指定的返回类型兼容。
可以在一个序列中传递参数,方法必须按同一序列接受它们。
示例 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP