College Board Unit 1
How it works
A return statement produces a value and immediately exits the method, so any code after it in that path never runs. Every path through a value-returning method must return something of the declared type; a void method returns no value and calling it in an expression does not compile. Returning a value is not the same as printing it, and a returned value is lost unless the caller stores or uses it.
Check that each branch returns, including the fall-through case after a loop.
Common error
Printing instead of returning, which produces visible output but no usable value and loses FRQ points.
Worked example
Java
int score = 12;
int adjusted = Math.max(0, score - 5);
System.out.println(adjusted);Output
7The call returns a value that can be assigned and used in a later expression.
Exercises
7.2.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
int a = 3;
int b = 8;
System.out.println(Math.max(a, b) + Math.min(a, b));Show solution
Output
11The return values 8 and 3 become operands of the addition.
7.2.2 · Write code
Write public static int clamp(int value, int low, int high), assuming low <= high. Return the nearest boundary if value lies outside the interval; otherwise return value.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
public static int clamp(int value, int low, int high) {
if (value < low) return low;
if (value > high) return high;
return value;
}Check your code
Java
System.out.println(clamp(-1,0,10));
System.out.println(clamp(5,0,10));
System.out.println(clamp(11,0,10));Expected output
0
5
10