Return Statement
1. What It Does (beginner)
return = send a value back + exit the method immediately. Two jobs: give answer, stop method. In void methods, bare return; just exits early.
2. Code — Value + Early Exit
public class Ret {
static int square(int x) {
return x * x; // sends 25 back, method ends HERE
// System.out.println("never!"); // unreachable ERROR!
}
static void check(int marks) {
if (marks < 0) return; // early exit on bad input (no value!)
System.out.println(marks >= 40 ? "Pass" : "Fail");
}
public static void main(String[] args) {
int s = square(5); // s = 25
System.out.println(s);
check(-5); // prints nothing (early return!)
check(75); // Pass
}
}
3. Rules (exam traps!)
- Return type must match:
intmethod mustreturn intValue;on every path (missing inelse= ERROR). voidmethod:return;ok (no value),return 5;ERROR.- Code after
return= unreachable, compile ERROR.
4. return vs break vs continue
return exits method (whole function ends). break exits loop/switch. continue skips one iteration.
5. Exam Points
- Method with return + early-exit
void— 5 marks, frequent. - Missing-return / unreachable errors — 3 marks, frequent trap.