Concept Flow - Return values
Start method
Execute statements
Return value reached?
No→Continue execution
Yes
Return value sent back
Method ends
The method runs its code until it hits a return statement, then sends the value back and stops.
public int add(int a, int b) { int sum = a + b; return sum; }
| Step | Action | Variables | Return? | Output |
|---|---|---|---|---|
| 1 | Method add called with a=3, b=4 | a=3, b=4 | No | |
| 2 | Calculate sum = a + b | a=3, b=4, sum=7 | No | |
| 3 | Return sum | a=3, b=4, sum=7 | Yes | 7 |
| 4 | Method ends | No |
| Variable | Start | After Step 2 | Final |
|---|---|---|---|
| a | 3 | 3 | 3 |
| b | 4 | 4 | 4 |
| sum | undefined | 7 | 7 |
Return values in Java methods: - Use 'return' to send a value back. - Method stops running after return. - Returned value matches method's declared type. - Code after return is not executed. - Returned value can be stored or used by caller.
return keyword do in a Java method?returnreturn keyword is used inside a method to send a value back to the caller.return does.int as return type to return an integer value.int and returns 5, which is an integer, so it is correct.public class Test {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(3, 4));
}
}public int multiply(int x, int y) {
int result = x * y;
}public static String checkNumber(int n) {
if (n > 0) return "Positive";
else if (n < 0) return "Negative";
else return "Zero";
}checkNumber(0) return?Pass the test and this pattern moves unknown