In Module 1.4, you passed information into methods through arguments. A method can also send information back to the code that called it. That information is its return value.
Imagine an airline application asking a Flight object how many seats remain. The Flight object owns the seat counts, so its method can calculate and return the answer.
public class Flight
{
public int capacity = 120;
public int bookedSeats = 86;
public int GetAvailableSeats()
{
return capacity - bookedSeats;
}
}For these field values, the calculation produces 34. The return statement sends that number back to the caller.
In the method header, int appears immediately before GetAvailableSeats:
public int GetAvailableSeats()It tells the caller what type of value to expect. Here, the method promises an integer. The expression after return must produce a value compatible with int.
Compare that with a method that performs an action without sending a value back:
public void PrintBoardingPass()
{
// Print the boarding pass.
}void means the method does not return a value. An int method has a result the caller can use.
Suppose an application calls flight.GetAvailableSeats(). The steps are:
GetAvailableSeats.capacity - bookedSeats for that Flight object.return sends the calculated integer to the caller.The method can return a calculation directly; it does not need a separate local variable just to hold the answer.
Two Flight objects can have different seat counts. Calling the same method on each object calculates its result from that object's fields.
Flight A: capacity = 120, bookedSeats = 86 -> returns 34
Flight B: capacity = 80, bookedSeats = 75 -> returns 5The method definition describes how to obtain the result; it does not store one shared answer for every Flight. Next, see how a class diagram records the method's return type.