المعاملات والقيم المُرجَعة
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
Lesson Overview
A method with no input and no output can only repeat itself. The useful ones take ingredients and give back a dish: add takes two numbers and gives back their sum; area takes a width and a height and gives back the area. This lesson shows how to declare those inputs (parameters), how to supply them (arguments), and how a method sends a result back with return.
It also introduces the single most important habit of method design: a method should usually compute a value or print a value, not both. A method that computes and returns can be reused, checked and formatted by whoever calls it. A method that computes and prints is locked to one use.
This lesson builds directly on Lesson 1 (declaring and calling a void method) and on Module 9 (types) and Module 12 (if). The next lesson shows how several methods can share one name.
Learning Objectives
By the end of this lesson you will be able to:
- Declare a method with parameters and a return type, such as
static int add(int a, int b). - Distinguish a parameter from an argument.
- Use
returnto send a value back and end the method. - Use the result of a call in an assignment or an expression.
- Explain the meaning of
voidand why its result cannot be assigned. - Write a method with several
returnstatements and know why every path must return. - Split a method that both computes and prints into two methods.
Written Explanation
Parameters in, a value out
Here is a method with two parameters and a return value:
static int add(int a, int b) {
return a + b;
}| Part | Here | Meaning |
|---|---|---|
| Return type | int | The kind of value the method hands back |
| Name | add | How you call it |
| Parameters | int a, int b | Named, typed variables that receive the inputs; each has its own type, separated by commas |
return | return a + b; | Sends the value back and ends the method |
The Oracle tutorial defines the signature of a method as its name plus its parameter types; for add that is add(int, int). Lesson 3 uses that idea heavily.
In the recipe-card picture: the parameters are the ingredient list at the top of the card, the return type is the dish the card produces, and return is the moment the finished dish is handed over.
Parameters versus arguments
Two words that beginners mix up:
- A parameter is the variable in the method declaration:
aandbabove. It is a placeholder. - An argument is the actual value you supply in a call: in
add(3, 4), the arguments are3and4.
When you call a method, Java evaluates each argument and copies its value into the matching parameter, in order: first argument to the first parameter, second to the second. The names do not have to match; the position does. Lesson 4 explains what "copy" implies.
Using the returned value
A call to a method that returns a value is an expression: it has a value, so it can go anywhere a value can.
int total = add(3, 4); // store it
System.out.println(add(10, 20) + add(1, 1)); // use it in an expression
if (add(2, 2) == 4) { ... } // test itIf you write add(3, 4); as a statement alone, Java accepts it but throws the result away, which is rarely what you wanted.
return ends the method
return does two things: it supplies the value and it leaves the method immediately. Any statement after a return on the same path never runs (the compiler rejects unreachable code). This allows several return statements, one per decision:
static double discountRate(double subtotal) {
if (subtotal >= 100) {
return 0.10;
}
if (subtotal >= 50) {
return 0.05;
}
return 0.0;
}Because each return leaves at once, no else is needed. Remember the rule from Module 12: order the tests from the most demanding to the least.
Every path must return. If a method has a non-void return type, the compiler insists that it cannot reach the closing brace without returning a value. A version of the method above that had only the first if would not compile:
Err2.java:6: error: missing return statement
}
^void: nothing comes back
A void method returns no value. It may still use a bare return; to stop early, but cannot return a value. Because there is nothing to hold, you cannot assign its result:
Err1.java:9: error: incompatible types: void cannot be converted to int
int x = hello();
^Use void for methods whose job is an action, such as printing a menu. Use a real return type whenever the caller will want the answer.
Type checks at the call
Java checks every call against the declaration, at compile time:
- The number of arguments must equal the number of parameters.
- Each argument must be convertible to the parameter type. An
intcan be passed where adoubleis expected (a widening conversion from Module 9), but adoublecannot be passed where anintis expected without a cast, because data could be lost. - The returned value must fit the declared return type.
Here are the two real compiler messages for those mistakes, calling add(int a, int b):
error: incompatible types: possible lossy conversion from double to int
int y = add(1, 2.5);
^
error: method add in class Err1 cannot be applied to given types;
required: int,int
found: int
reason: actual and formal argument lists differ in lengthCompute or print, not both
Compare two versions of the same job:
static void addAndPrint(int a, int b) { // locked to printing
System.out.println(a + b);
}
static int add(int a, int b) { // reusable
return a + b;
}With add, the caller decides what to do: print it, store it, add it to a running total, compare it, or format it with two decimals. With addAndPrint, the number goes to the screen and is gone. A method that returns a value can also be tested by checking the value, which you will do in the testing module; testing something that only prints is much harder.
The rule: methods that do the work return a result; methods that show results print. Keep them separate and combine them in the caller, e.g. printArea(w, h) calls area(w, h).
Examples
Example 1: add (simple)
public class Add {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int total = add(3, 4);
System.out.println(total);
System.out.println(add(10, 20) + add(1, 1));
}
}Output (JDK 21):
7
32Trace add(3, 4): 3 is copied into a, 4 into b, the body computes 7, return hands it back, and the call expression becomes 7. In the second println, two calls produce 30 and 2, and + adds them to give 32.
Example 2: area, with separate printing (practical)
public class Area {
static double area(double width, double height) {
return width * height;
}
static void printArea(double width, double height) {
System.out.println("Area: " + area(width, height));
}
public static void main(String[] args) {
double wall = area(4.5, 2.0);
double floor = area(5, 3); // ints widen to double
System.out.println(wall + floor);
printArea(2, 3);
}
}Output:
24.0
Area: 6.0area computes and returns; printArea only shows and delegates the maths to area. Notice area(5, 3): the int arguments are widened to double automatically. Because area returns the number, main could add the wall and floor areas, something a print-only method could never support.
Example 3: a price with discount and tax (realistic)
A small checkout rule: a subtotal of 100 or more earns 10 percent off, 50 or more earns 5 percent, and tax is added after the discount.
public class Shop {
static double discountRate(double subtotal) {
if (subtotal >= 100) {
return 0.10;
}
if (subtotal >= 50) {
return 0.05;
}
return 0.0;
}
static double finalPrice(double subtotal, double taxRate) {
double discounted = subtotal * (1 - discountRate(subtotal));
return discounted * (1 + taxRate);
}
public static void main(String[] args) {
System.out.println(finalPrice(40, 0.25));
System.out.println(finalPrice(80, 0.25));
System.out.println(finalPrice(200, 0.25));
}
}Output:
50.0
95.0
225.0Each method does one job. finalPrice calls discountRate and uses its result inside an expression. If the discount policy changes, only discountRate changes. A tax rate of 0.25 is chosen here only to keep the sums tidy; real rates vary, and money in real systems needs more care than double (a topic for later).
Backend Insight
Almost every backend method has the shape "inputs in, result out": calculateShipping(weight, zone), isEmailValid(text), totalFor(order). The caller then decides what to do with the result: send it in a response, store it, or log it.
Mixing computation with printing hurts in a service. A web application has no console to print to; it needs the value so it can put it into a response. Likewise, a method that only prints cannot be tested without capturing the screen. Methods that return values are the building blocks that other layers (an HTTP handler, a scheduled job, a test) can all reuse.
Common Mistakes
Mistake 1: Computing and printing in one method
static void total(int a, int b) { System.out.println(a + b); }
int sum = total(2, 3); // error: void cannot be converted to intReturn the value and let the caller print it.
Mistake 2: Forgetting return on some path
If an if returns but no statement follows it, the compiler reports missing return statement. Add a final return (or an else) so that every path hands something back.
Mistake 3: Wrong number or type of arguments
add(1) fails because the argument list is too short; add(1, 2.5) fails because 2.5 would lose data in an int. Read the required: and found: lines of the error: they list what the method expects and what you gave.
Mistake 4: Ignoring the returned value
Writing add(3, 4); alone compiles but does nothing useful. Store or use the result: int total = add(3, 4);.
Mistake 5: Mixing up parameters and arguments
Parameters are in the declaration; arguments are in the call. Changing a parameter's name inside the method does not require changing the caller, since values are matched by position.
Exercises
Try each exercise yourself before opening the solutions.
Level A: Foundation
A1. For static int square(int n) { return n * n; }, name the return type, the parameter, and the value of square(5).
أظهر الحل A1
A1. Return type int, parameter n (of type int), and square(5) is 25.
A2. What is the difference between a parameter and an argument? Point to both in triple(7) where static int triple(int x) { return x * 3; }.
أظهر الحل A2
A2. A parameter is the variable named in the declaration; an argument is the value given in the call. In triple(7), 7 is the argument and x (in the declaration) is the parameter.
A3. Why does String s = hello(); fail when hello is declared static void hello()?
أظهر الحل A3
A3. hello is void, so it produces no value to store in a String. The compiler reports that void cannot be converted to String.
Level B: Application
B1. Write static double average(double a, double b) and call it so the program prints the average of 7 and 10.
أظهر الحل B1
B1.
static double average(double a, double b) {
return (a + b) / 2;
}
public static void main(String[] args) {
System.out.println(average(7, 10)); // 8.5
}B2. The method below is meant to return the larger of two ints but does not compile. Say why and fix it.
static int larger(int a, int b) {
if (a > b) {
return a;
}
}أظهر الحل B2
B2. If a > b is false, the method reaches the closing brace without returning, so the compiler reports missing return statement. Fix: add return b; after the if (or use else { return b; }).
B3. Rewrite static void celsiusToF(double c) { System.out.println(c * 9 / 5 + 32); } so that it computes and returns, then show the call that prints 100 degrees Celsius in Fahrenheit.
أظهر الحل B3
B3.
static double celsiusToF(double c) {
return c * 9 / 5 + 32;
}
// in main:
System.out.println(celsiusToF(100)); // 212.0Level C: Challenge
C1. Write static boolean isAdult(int age) (18 or over counts as adult) and a second method static String describe(int age) that uses isAdult and returns "adult" or "minor". Print describe(17) and describe(18). Explain why isAdult should not print.
أظهر الحل C1
C1.
static boolean isAdult(int age) {
return age >= 18;
}
static String describe(int age) {
if (isAdult(age)) {
return "adult";
}
return "minor";
}
// in main:
System.out.println(describe(17)); // minor
System.out.println(describe(18)); // adultisAdult answers a yes/no question that other code (access checks, pricing) may need. If it printed, those callers could not use the answer.
C2. Write static int clamp(int value, int low, int high) that returns low if value is below it, high if above it, otherwise value. List three test calls that cover both boundaries and the middle, with expected results worked out by hand first.
أظهر الحل C2
C2.
static int clamp(int value, int low, int high) {
if (value < low) {
return low;
}
if (value > high) {
return high;
}
return value;
}Calls and expected results (worked out before running): clamp(-5, 0, 10) gives 0; clamp(15, 0, 10) gives 10; clamp(7, 0, 10) gives 7. Adding the exact boundaries, clamp(0, 0, 10) gives 0 and clamp(10, 0, 10) gives 10.
Mini Challenge
Write a small "rectangle toolkit" with area(w, h), perimeter(w, h) and printReport(w, h). The first two return double; the third prints one line that uses both. In main, call printReport for two different rectangles.
Check your work: area and perimeter contain no println; printReport contains the only printing; changing a formula requires editing exactly one method.
Summary & Next Lesson
Key takeaways
- Parameters are the typed variables in a declaration; arguments are the values supplied in a call, matched by position.
- The return type says what comes back;
voidmeans nothing does and its result cannot be assigned. returnsupplies the value and ends the method at once; with a non-voidtype, every path must return.- A call that returns a value is an expression: store it, combine it, or test it.
- Prefer methods that compute and return, and separate methods that print.
Next lesson
You have seen that a method is identified by its name plus parameter types. The next lesson, "Method signatures and overloading", shows how several methods can share one name, such as max(int, int) and max(double, double), and how Java decides which one a call means.
Self-check
- What do
intanda, bmean instatic int add(int a, int b)? - What is an argument?
- What does
returndo besides giving back a value? - Why is
int x = greet();an error whengreetisvoid? - Why is it better for
areato return a number than to print it?
أظهر الإجابات
int(first) is the return type;int a, int bdeclare twointparameters. (addin the middle is the name.)- The actual value supplied in a call, copied into the matching parameter.
- It ends the method immediately, so later statements on that path do not run.
- A
voidmethod gives back no value, so there is nothing to store inx. - The caller can reuse the value: store it, add it to other values, format it or test it. Printing locks the number to the screen.
References
- Oracle, Defining Methods. Verified: a method declaration's components (return type, name, parameter list, body),
voidfor no result, and the definition of a signature as name plus parameter types. - Oracle, Passing Information to a Method or a Constructor. Verified: parameters and arguments, and that arguments are passed by value.
- Compiler messages and program outputs above were produced by compiling and running the code with JDK 21 (
javac 21.0.10). The statements aboutmissing return statementand unreachable code describe the compiler behaviour seen there; I did not locate the exact JLS paragraphs for them.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.