← Java tutorials

LESSON 13 / 40 · FREE TUTORIAL

Parameters and Return Values

Parameter return and overloading

100–120 minutesThis chapter uses JDK 21 and does not require the preview function.Basic Advanced

WHAT YOU WILL MAKE

Making a Practice Injury Calculator

Can use parameters to feed data into methods; can use return to bring results back to the caller; can write boolean query methods and understand overloading; and finally complete a damage calculator that considers weapons, sharpness, critical hits, and armor. Prerequisites: static methods will be defined and called. The recipe card in the previous lesson only had fixed materials; in this lesson, it is equipped with a material slot and a finished product outlet.

Before you start: It is recommended to complete Lesson 12 first

Material tank and finished product outlet of method
  1. Actual parametersProvide this material
  2. MethodCalculated by contract
  3. Return valueThe caller receives the result

01 / 15

Before you begin: Put the examples in the right place

This chapter uses JDK 21 and does not require the preview function. A complete program is given for each common example, saved with annotated file names. Multiple examples are placed in their own folders to avoid auxiliary classes with the same name.

Terminal command: Replace the Chinese placeholder with the actual name

javac -encoding UTF-8 ExampleFile.java
java ExampleClass

Class names are case-sensitive. If the complete challenge code is divided into multiple sections, please connect them in the same file in order. Do not create separate classes for the continued sections. Run verification only lists the program output; additional input sequences are provided where input is required.

02 / 15

Enchanting table does not accept telepathy

The enchanter asked: "How much is the basic damage? How sharp is it? Is it a critical hit this time?" The player replied: "Guess." The enchanter closed the book: the method is not telepathic.

The parameters are the material slots in the method definition, and the actual parameters are the data actually put in when calling. The return value is the finished product handed over after the method completes the calculation.

The method requires an explicit material slot
  1. baseBasic damage, double
  2. sharpSharpness level, int
  3. criticalCritical hit status, boolean
  4. armorTarget armor, double

Starting with four questions

  • Where do formal parameters and actual parameters appear respectively?
  • Why must multiple parameters be passed in order?
  • What is the difference between void and methods with return values?
  • Why can't overloading just change the return type?

03 / 15

Parameter slot and actual parameter material

double base and int level are formal parameters; 7.0 and 3 are actual parameters. When the call occurs, the actual parameter values ​​are entered into the corresponding parameters.

The route of data through the method
  1. Actual parametersValue provided at call location
  2. Shape participates in calculationMethod uses a copy of the value
  3. returnReturn the result to the calling place

L13Example02.java · Complete independent example

public class L13Example02 {
    static double damage(double base, int level) { return base + level * 1.5; }
    public static void main(String[] args) {
        System.out.println(damage(7.0, 3));
        System.out.println(damage(5.0, 0));
        System.out.println(damage(8.0, 2));
    }
}

Output

11.5
5.0
11.0

04 / 15

Multiple parameters cannot be placed in the wrong format

If the two parameter types are the same, Java may still compile after passing them reversely. The house will change from 9×7 to 7×9, and then you can confidently say that you did not report an error.

The parameter sequence is the workbench grid sequence
  1. widthThe first item, horizontal width
  2. heightSecond item, vertical height
  3. Correct call9,7 gets width 9 height 7
  4. Transmission7,9 can be compiled but the meaning changes

L13Example03.java · Complete independent example

public class L13Example03 {
    static void describeArea(int width, int height) {
        System.out.println(width + " x " + height);
    }
    public static void main(String[] args) {
        int houseWidth = 9, houseHeight = 7;
        describeArea(houseWidth, houseHeight);
        describeArea(houseHeight, houseWidth);
    }
}

Output

9 x 7
7 x 9

Call Check

  • When there are too many parameters, each actual parameter should be on a separate line.
  • Use variable names with clear meanings and do not pile numbers directly.
  • Test values with different width and height, and it is easier to see when the reverse is passed.

05 / 15

return Send the result back

The method with a return value is like a workbench: put in the materials and take out the finished products. Once return is executed, the method ends immediately and the value is handed to the caller. In this example, each material is limited to 0 to 64; returning 0 for illegal input is a convention of this method, and it is not a strategy that should be adopted by all calculation methods.

The route of data through the method
  1. Actual parametersValue provided at call location
  2. Shape participates in calculationMethod uses a copy of the value
  3. returnReturn the result to the calling place

L13Example04.java · Complete independent example

public class L13Example04 {
    static int torchCount(int coal, int sticks) {
        if (coal < 0 || sticks < 0 || coal > 64 || sticks > 64) return 0;
        return Math.min(coal, sticks) * 4;
    }
    public static void main(String[] args) {
        int torches = torchCount(7, 10);
        System.out.println(torches);
        System.out.println(torchCount(2, 5) >= 8);
    }
}

Output

28
true

06 / 15

Return in advance to guard the boundary

Boundary checking is placed at the beginning of the method to keep the normal formulas that follow clear. Returning early is not skipping class, but the security guard asking the negative creeper to leave the workbench.

Bad input is blocked at the door first
  1. Negative quantityReturn 0 directly
  2. Normal quantityCalculated by formula
  3. Oversize materialThis example is also rejected if it exceeds 64
  4. Sharpness levelCorrected to 0 to 5

L13Example05.java · Complete independent example

public class L13Example05 {
    static int torchCount(int coal, int sticks) {
        if (coal < 0 || sticks < 0 || coal > 64 || sticks > 64) return 0;
        return Math.min(coal, sticks) * 4;
    }
    static int safeLevel(int level) { return Math.max(0, Math.min(5, level)); }
    public static void main(String[] args) {
        System.out.println(torchCount(-1, 3));
        System.out.println(torchCount(0, 64));
        System.out.println(safeLevel(9));
    }
}

Output

0
0
5

07 / 15

boolean method answers true or false

Methods that return boolean are suitable for answering questions. The call site reads like a sentence, so the method name should sound like a question.

Query method like redstone detector
  1. canCraftPickaxeOnly check material quantity
  2. trueMaterials: at least 3 diamonds and 2 wooden sticks
  3. falseThere is a lack of material
  4. Calling pointDetermine follow-up actions based on the answer

L13Example06.java · Complete independent example

public class L13Example06 {
    static boolean canCraftPickaxe(int diamonds, int sticks) {
        return diamonds >= 3 && sticks >= 2;
    }
    public static void main(String[] args) {
        System.out.println(canCraftPickaxe(5, 1));
        if (canCraftPickaxe(3, 2)) System.out.println("Enough material");
    }
}

Output

false
Enough material

08 / 15

Different formulas of the same name method

Overloading allows related operations to share a method name, but the parameter lists must be different. It is suitable for "same action, different material combinations".

Overload shared name parameter list is different
  1. Single parameter versionItem name, default quantity 1
  2. Dual parameter versionItem name and quantity
  3. Reloading rulesParameter lists must be different
  4. CallJava selects version by parameters

L13Example07.java · Complete independent example

public class L13Example07 {
    static void giveItem(String item) { giveItem(item, 1); }
    static void giveItem(String item, int count) {
        System.out.println(item + " x" + count);
    }
    public static void main(String[] args) {
        giveItem("diamond");
        giveItem("Torch", 16);
    }
}

Output

diamond x1
Torch x16

09 / 15

How to choose overloading in Java

When an overloaded method is called, Java looks at the number and type of actual parameters. If both versions are equally suitable, a "Which door should I enter" compilation error will occur.

The actual parameter type determines which track to take
  1. show(int)Integer 3 selects this version
  2. show(double)3.5 Select this version
  3. Type conversionInteger can be converted into double
  4. NOTECannot rely solely on return type selection

L13Example08.java · Complete independent example

public class L13Example08 {
    static void show(int n) { System.out.println("Integer " + n); }
    static void show(double n) { System.out.println("Decimal " + n); }
    public static void main(String[] args) {
        show(3);
        show(3.5);
    }
}

Output

Integer 3
Decimal 3.5

10 / 15

Damage formula split calculation

Do not cram complex formulas into one line. Calculate weapons and sharpness first, then deal with critical hits, and finally deduct armor, and use Math.max to prevent damage from becoming negative.

The route of data through the method
  1. Actual parametersValue provided at call location
  2. Shape participates in calculationMethod uses a copy of the value
  3. returnReturn the result to the calling place

L13Example09.java · Complete independent example

public class L13Example09 {
    static double damage(double base, int sharp,
            boolean critical, double armor) {
        if (!Double.isFinite(base) || !Double.isFinite(armor)) return 0;
        base = Math.max(0, Math.min(100, base));
        sharp = Math.max(0, Math.min(5, sharp));
        armor = Math.max(0, Math.min(100, armor));
        double raw = base + sharp * 1.5;
        if (critical) raw *= 1.5;
        return Math.max(0, raw - armor);
    }
    public static void main(String[] args) {
        System.out.println(damage(7, 2, false, 5));
        System.out.println(damage(7, 5, true, 0));
    }
}

Output

5.0
21.75

11 / 15

Three types of tests reveal loopholes

Testing is not about "clicking and running a few times." Each test must have inputs, expected and actual results.

Normal boundary error testing is indispensable
  1. NormalNormal hits and critical hits
  2. BorderLevel 0 or 5, Armor 0
  3. ErrorNegative numbers and non-finite decimals
  4. CompareDecimal testing allows minimal error

L13Example10.java · Complete independent example

public class L13Example10 {
    static double damage(double base, int sharp,
            boolean critical, double armor) {
        if (!Double.isFinite(base) || !Double.isFinite(armor)) return 0;
        base = Math.max(0, Math.min(100, base));
        sharp = Math.max(0, Math.min(5, sharp));
        armor = Math.max(0, Math.min(100, armor));
        double raw = base + sharp * 1.5;
        if (critical) raw *= 1.5;
        return Math.max(0, raw - armor);
    }
    public static void main(String[] args) {
        double result = damage(7, 2, false, 5);
        System.out.println(Math.abs(result - 5.0) < 0.0001);
        System.out.println(damage(-2, 9, false, -1));
        System.out.println(damage(Double.NaN, 2, false, 0));
    }
}

Output

true
7.5
0.0
Acceptance and inspection forms
CategoryEnter base, sharp, critical, armorExpected
Normal7, 2, false, 55.0
Border0, 0, false, 00.0
Border7, 5, true, 021.75
Correction-2, 9, false, -17.5
ErrorNaN, 2, false, 00.0

12 / 15

Parameters and Return Value Fault Clinic

Read the method header first, it is the contract. The calling site must provide the correct number and type of arguments; every reachable path to a non-void method must return a value.

Four kinds of faults can be located from the method contract
  1. Leak returnThere is a path but no return
  2. Overload conflictThe parameters are the same, only the return type is changed
  3. Few actual parametersQuantity does not match
  4. RepairCheck method contract

BadReturn.java · Intentional error example

public class BadReturn {
    static int count(int n) { if (n > 0) return n; }
    public static void main(String[] args) { }
}

BadOverload.java · Intentional error example

public class BadOverload {
    static int value(int n) { return n; }
    static double value(int n) { return n; }
    public static void main(String[] args) { }
}

13 / 15

Challenge Damage Calculator

Create new DamageCalculator.java. The challenge method is to protect negative input, limit the sharpness to 0 to 5, and then calculate the final damage.

Four inputs merge into one testable method
  1. Enter the contractbase and armor range from 0 to 100
  2. Level contractsharp corrected to 0 to 5
  3. Calculation rulesCustom practice injuries
  4. Export contractReturn a finite and non-negative value

DamageCalculator.java · Complete stand-alone example

public class DamageCalculator {
    static double damage(double base, int sharp,
            boolean critical, double armor) {
        if (!Double.isFinite(base) || !Double.isFinite(armor)) return 0;
        base = Math.max(0, Math.min(100, base));
        sharp = Math.max(0, Math.min(5, sharp));
        armor = Math.max(0, Math.min(100, armor));
        double raw = base + sharp * 1.5;
        if (critical) raw *= 1.5;
        return Math.max(0, raw - armor);
    }
    public static void main(String[] args) {
        System.out.println(damage(7, 2, false, 5));
        System.out.println(damage(7, 5, true, 0));
        System.out.println(damage(-2, 9, false, -1));
    }
}

Output

5.0
21.75
7.5

14 / 15

Expansion tasks and clearance review

Each file must write at least three tests, among which there must be a boundary value.

The third-level task makes the formula card truly changeable.
  1. Wooden PickaxeMaterial calculation and boundary
  2. Iron PickaxeCoordinate distance method
  3. Diamond PickaxeAdd differentiated overloading
  4. ReviewInterpret formal and actual parameters

Third gear operation

  • Wooden pickaxe: Write torchCount(coal, sticks) to return the maximum number of torches that can be synthesized.
  • Iron Pickaxe: Write distance(x1, y1, x2, y2), and return the straight-line distance between two points.
  • Diamond Pickaxe: Overload three kinds of giveItem, supporting default quantity, specified quantity and specified player respectively.
Acceptance and inspection forms
Self-evaluationCanStill need to practice
I can explain the formal and actual parameters□□
I can use return□□
I can determine whether the overload is established□□

15 / 15

Own acceptance record

Write expectations before running, and record actual results after running. Normal cases show that the program does things; edge cases show that it knows when to stop; error cases show that it rejects unreasonable requests.

Write the evidence into the record
CategoryInput of your choiceExpectation and actual
NormalA common value or a successful operationIs it consistent line by line?
BorderMinimum value, maximum value and adjacent valueIs there one less square and one more step?
ErrorIllegal quantity, missing object or incorrect syntaxExplicitly reject? Is the status maintained?
  • Write a bug as: triggering conditions, phenomena, causes, and minimal repairs.
  • Organize a rule worth remembering and explain it in your own words. Don't just copy the definition.
  • Change an example, keep a record of the test, and let the results prove your understanding.

TAKE IT WITH YOU

Take the lesson offline

The complete lesson, code, diagrams and exercises, in your preferred language.