Skip to main content

Section 3.2 Introducing Methods

Prerequisites:
Think of methods like your favorite recipes - write them once, use them many times! Just as you wouldnโ€™t want to write down a cookie recipe every time you bake, Java methods let us write code once and reuse it wherever needed.
Note: You might hear these called "functions" in other languages like Python or JavaScript. In Java, we typically say "methods" when the code belongs to a class.
In this section, weโ€™ll learn:
  • How to spot code that could be turned into methods (using our Design Recipe skills)
  • How Java handles method parameters (itโ€™s like passing notes in class!)
  • Why methods are just the first step toward organizing our code

Subsection 3.2.1 Why Do We Need Methods?Repeated Logic Example

Letโ€™s start with a real problem. Imagine youโ€™re making a simple game where a player gains health and gold after winning fights:
public class IntroMethods1 {
    public static void main(String[] args) {
        int playerHealth = 10;
        int playerGold   = 50;

        // First victory
        playerHealth += 5;
        playerGold   += 10;

        // Second victory
        playerHealth += 5;
        playerGold   += 10;

        System.out.println("Health: " + playerHealth);
        System.out.println("Gold:   " + playerGold);
    }
}
Hold up! Did you notice we wrote the same code twice? Just like copying homework isnโ€™t the best idea, copying code can lead to problems. What if we need to change how much gold a player gets? Weโ€™d have to find and update every copy!
Key Insight: When you find yourself copy-pasting code, itโ€™s usually a sign you need a method!

Subsubsection 3.2.1.1 Quick Check โœ“

Before moving on, make sure you can answer:

Subsection 3.2.2 Creating Your First Method

Think of a method like a vending machine:
Hereโ€™s the basic recipe:
public static returnType methodName(parameters) {
    // method body
    return something; // if needed
}
Letโ€™s break this down:
For example, in public static int addNumbers(int first, int second):
Example:
public static int addTwoNumbers(int a, int b) {
    int sum = a + b;
    return sum;  // must match the 'int' return type
}
Compiler moment: If you accidentally do
public static int addTwoNumbers(String a, int b) { ... }
the compiler flags an incompatible type error when you try addTwoNumbers(3, 5). It expects (String, int), not (int, int). The compiler is your "early alert system" for mismatched parameter types.

Subsection 3.2.3 Trying a void Methodโ€”Why Doesnโ€™t It Work?

Letโ€™s trace what happens when we run this code:
public static void awardVictory(int health, int gold) {
    // health is now a COPY of playerHealth (10)
    health += 5;  // health becomes 15, but only inside this method
    // gold is a COPY of playerGold (50)
    gold += 10;   // gold becomes 60, but only inside this method
    // When method ends, copies are discarded!
}
// In main:
playerHealth = 10;  // Original stays 10
playerGold = 50;    // Original stays 50
Think about it: If you make a photocopy of a document and write on the copy, does it change the original? Thatโ€™s what Java does with int parametersโ€”it makes copies!
The Fiasco: What options do we have? Letโ€™s think through this like the Design Recipe taught us...
  • Could we use void and hope Java changes the originals? (Noโ€”we just saw why!)
  • Could we return both values somehow? (Not directlyโ€”methods return one thing)
  • Could we... wait... what if we return the new value and store it back? (Yes!)
In main() In method()
playerHealth = 10 health = 10 (copy)
playerHealth still 10 health += 5
(unchanged) (copy discarded)

Subsection 3.2.4 Returning New Values to Fix It

(Implementation, Step 3 & 4: We refine and retest)
We can fix it by returning the new integer and storing it in the caller. Letโ€™s do two separate methods for clarity:
Now, each method returns the updated int, and we assign it back into playerHealth or playerGold. If you wanted "gold +12" instead of "+10," youโ€™d edit increaseGold() in one place.

Subsection 3.2.5 Many Fields โ†’ Multiple Parameters Fiasco

Remember how the Design Recipe warned us about code thatโ€™s "trying to do too much"? Letโ€™s count the ways this approach can go wrong:
  • What if we add more player stats? awardVictory(health, gold, xp, mana, stamina, luck)
  • What if we need two players? awardVictory(player1Health, player1Gold, player1Xp)
  • What if we accidentally mix up the order? awardVictory(gold, health)โ€”oops!
The compiler canโ€™t save us hereโ€”it sees (int, int) and thinks "looks good!" even if weโ€™ve mixed up which int is which. There must be a better way...
Design Recipe perspective:
  • We identified repeated logic โ†’ used methods.
  • But we still juggle many separate variables. The next step? "Bundle them in one container." In Java, that container is a class. Then we can do player1.heal(5) without passing health1, xp1, gold1.
Weโ€™ll see that in the upcoming Introducing Classes section, including how encapsulation protects those fields from accidental misuse.

Subsection 3.2.6 What Weโ€™ve Learned

Big Ideas:
Coming Up Next: Weโ€™ll learn about classes - a way to keep related data and methods together, like keeping all your school supplies in one backpack instead of carrying them separately!

Subsection 3.2.7 Your Turn

Try this exercise to practice what youโ€™ve learned. Remember: itโ€™s okay if you donโ€™t get it perfect the first time - thatโ€™s how we learn!
Define public static double convertFtoC(double tempF), returning the Celsius result. Test by printing convertFtoC(32).
Hereโ€™s some starter code to get you started. To prevent compiler errors, weโ€™ve included a return statement with a valid data type, though the value itself may be just a placeholder. Be sure to update the return value accordingly as you implement the actual logic.

Subsection 3.2.8 Common Pitfalls to Watch Out For

  • Forgetting to Return: If your method declares a return type, every path must return something
    public static int bad(int x) {
        if (x > 0) {
            return x;
        }
        // Error! What if x <= 0?
    }
    
  • Return Type Mismatch:
    public static int oops() {
        return 3.14; // Error! Can't return double where int expected
    }
    
  • Parameter Type Confusion:
    public static void example(int x) { }
    
    double d = 3.14;
    example(d);  // Error! Can't pass double where int expected
    

Subsection 3.2.9 Quick Reference

Method Syntax:
public static returnType methodName(type1 param1, type2 param2) {
    // method body
    return value;  // if non-void
}
Key Points:
Design Recipe Steps:
  1. Forumulate data definitions
  2. Write method signature
  3. Test with examples
  4. Implement and verify

Subsection 3.2.10 Exercises: Introducing Methods

Checkpoint 3.2.1. Multiple Choice: The Repeated Code Problem.

In the example where we repeatedly wrote playerHealth += 5; playerGold += 10; for each victory, which of the following best explains why that repeated code is problematic?
  • Java prohibits writing the same code more than once in a file.
  • Java doesnโ€™t forbid thatโ€”it simply becomes difficult to maintain.
  • Whenever we need to change the reward amounts, we must edit multiple places, risking inconsistencies.
  • Exactly! Repetition leads to fragile code and potential errors when updating the logic.
  • Copy-pasting code only matters in Python, not in Java.
  • Repetition is a problem in any languageโ€”it makes maintenance harder.
  • We can only use repeated code if we mark it static first.
  • static doesnโ€™t address the real issue of maintenance overhead when logic changes.

Checkpoint 3.2.2. Parsons: Convert Repeated Logic to Methods.

Rearrange the following lines to form a single, valid Java program named VictoryGame. It should:
  • Have a class VictoryGame.
  • Define two methods: awardVictoryHealth and awardVictoryGold, each returning the updated int.
  • Use these methods in main to update playerHealth and playerGold from 10 and 50 to 15 and 60, respectively.
  • Print the final health and gold to the console.
There is only one sensible ordering in which all braces match and the code compiles and runs. Arrange the blocks carefully!

Checkpoint 3.2.3. True/False: Javaโ€™s Pass-by-Value.

    In Java, when we pass an int or double to a method, the method receives a copy of that value, not the original variable.
  • True.

  • Java always passes primitive types by value, so changing the parameter inside the method does not affect the original variable outside the method.
  • False.

  • Java always passes primitive types by value, so changing the parameter inside the method does not affect the original variable outside the method.

Checkpoint 3.2.4. Short Answer: Why Did the void Method Fail to Update Player Stats?

In the example, we tried public static void awardVictory(int health, int gold) hoping it would directly update playerHealth and playerGold, but it didnโ€™t work as intended. In 2-3 sentences, explain why void methods didnโ€™t update the original variables, and how returning a new value instead solves the problem.
Solution.
Sample Solution: Java passes health and gold as copies, so changing them in the void method does not affect the original playerHealth or playerGold. By returning the updated values (e.g., return currentHealth + 5;), we can reassign playerHealth to that new value in the main method, ensuring the original variable changes.

Subsubsection 3.2.1 Bonus: More on Naming

  • Method names typically start with a lowercase letter and use "camelCase" for additional words: increaseGold(), addTwoNumbers().
  • They must follow Javaโ€™s identifier rules (no spaces, canโ€™t start with a digit, etc.).
If you forget these rules, or pass arguments of the wrong type, your compiler is your first line of defenseโ€”helping you spot errors early, in true design-recipe spirit.
You have attempted of activities on this page.