return statement ส่งควบคุมโปรแกรมกลับไปยัง caller ของเมธอด ทุกเมธอดใน Java ต้องประกาศ return type เป็นบังคับ อาจเป็น primitive type (int, float, double), reference type หรือ void (ไม่คืนค่า)
ข้อสำคัญเกี่ยวกับการคืนค่า:
- ชนิดข้อมูลที่คืนต้องเข้ากันได้กับ return type ที่ประกาศ เช่น return type เป็น boolean ไม่สามารถคืน integer ได้
- ตัวแปรรับค่าที่คืนต้องเข้ากันได้กับ return type ของเมธอด
- พารามิเตอร์ต้องส่งในลำดับ และเมธอดต้องรับในลำดับเดียวกัน
ตัวอย่าง 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