Methods & Modularization

IB Syllabus: B2.3.4 - Construct functions and modularization.

Table of Contents

  1. Key Concepts
    1. Anatomy of a Method
  2. Worked Examples
    1. Example 1: void Method – No Return Value
    2. Example 2: Method with Return Value
    3. Example 3: Methods Calling Other Methods
    4. Example 4: boolean Return – Validation Helper
  3. Scope: Local vs Global Variables
    1. Local Variables
    2. Global (Class-Level) Variables
    3. When to Use Which?
  4. Why Modularize?
  5. Quick Check
  6. Trace Exercise
  7. Code Completion
  8. Spot the Bug
  9. Output Prediction
  10. Practice Exercises
    1. Core
    2. Extension
    3. Challenge
  11. GitHub Classroom
  12. Connections

Key Concepts

A method is a named, reusable block of code that performs a specific task. Instead of writing the same logic multiple times, you define it once and call it wherever needed.

Term Meaning
Method A named block of code that performs a task
Parameter A variable in the method header that receives data
Argument The actual value passed when calling the method
Return type The type of value the method sends back (int, double, boolean, String, etc.)
void The method performs an action but does not return a value
Modularization Breaking a program into smaller, independent methods
Scope Where a variable can be accessed (local vs global)

Anatomy of a Method

//  returnType  methodName(parameterType parameterName)
public static int add(int a, int b) {
    return a + b;
}
Part What it means
public static Access and scope modifiers (more on these in OOP)
int Return type – what type of value the method sends back
add Method name (camelCase by convention)
int a, int b Parameters – placeholders for the values passed in
return a + b The result sent back to whoever called the method

Use void when a method performs an action but does not return a value:

public static void printGreeting(String name) {
    System.out.println("Hello, " + name + "!");
}

Parameter vs Argument: A parameter is the variable name in the method header (String name). An argument is the actual value you pass when calling the method ("Alice"). This distinction appears in IB exam questions.


Worked Examples

Example 1: void Method – No Return Value

A void method performs an action (like printing) but does not send a value back.

public class Greeter {
    public static void main(String[] args) {
        printSeparator();
        System.out.println("Welcome to the Grade Manager!");
        printSeparator();
    }

    public static void printSeparator() {
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
    }
}

Output:

~~~~~~~~~~~~~~~~~~~~~~~~
Welcome to the Grade Manager!
~~~~~~~~~~~~~~~~~~~~~~~~

How it works:

  • printSeparator() is called twice from main. Each time, it prints the same line of = characters.
  • The method has no parameters (empty parentheses) and no return value (void).
  • This avoids duplicating the print statement – if you want to change the separator, you change it in one place.

Example 2: Method with Return Value

A method that returns a value uses a return type (like int, double, boolean) and a return statement.

public class Calculator {
    public static void main(String[] args) {
        int result = add(5, 3);
        System.out.println("Sum: " + result);
        System.out.println("Product: " + multiply(4, 7));
    }

    public static int add(int a, int b) {
        return a + b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }
}

Output:

Sum: 8
Product: 28

How it works:

  • add(5, 3) passes arguments 5 and 3 to parameters a and b. The method computes a + b and returns 8.
  • The returned value can be stored in a variable (result) or used directly inside println.

Example 3: Methods Calling Other Methods

Methods can call other methods. This is where modularization becomes powerful – each method does one focused job.

public class GradeReport {
    public static void main(String[] args) {
        int[] grades = {85, 92, 78, 95, 88};
        printReport(grades);
    }

    public static void printReport(int[] grades) {
        printSeparator();
        System.out.println("Grade Report");
        printSeparator();
        printGrades(grades);
        double avg = calculateAverage(grades);
        System.out.println("Average: " + avg);
        printSeparator();
    }

    public static void printSeparator() {
        System.out.println("~~~~~~~~~~~~~~~~~~~~~");
    }

    public static void printGrades(int[] grades) {
        for (int i = 0; i < grades.length; i++) {
            System.out.println("Student " + (i + 1) + ": " + grades[i]);
        }
    }

    public static double calculateAverage(int[] grades) {
        int total = 0;
        for (int i = 0; i < grades.length; i++) {
            total = total + grades[i];
        }
        return (double) total / grades.length;
    }
}

Output:

~~~~~~~~~~~~~~~~~~~~~
Grade Report
~~~~~~~~~~~~~~~~~~~~~
Student 1: 85
Student 2: 92
Student 3: 78
Student 4: 95
Student 5: 88
Average: 87.6
~~~~~~~~~~~~~~~~~~~~~

How it works:

  • main calls printReport, which calls printSeparator, printGrades, and calculateAverage.
  • Each method has a single, clear job. main reads like a high-level summary of the program.
  • calculateAverage returns a double that printReport stores and prints.

Try it: Look at the MiniProj code you wrote earlier this year (the GradeArray project). Can you identify sections that could be extracted into separate methods?


Example 4: boolean Return – Validation Helper

Methods that return boolean are useful for checking conditions. They make your code read like English.

public class Validator {
    public static void main(String[] args) {
        int score = 85;
        if (isValidGrade(score)) {
            System.out.println(score + " is a valid grade.");
        } else {
            System.out.println(score + " is not valid.");
        }
        System.out.println("Is 150 valid? " + isValidGrade(150));
    }

    public static boolean isValidGrade(int grade) {
        return grade >= 0 && grade <= 100;
    }
}

Output:

85 is a valid grade.
Is 150 valid? false

Scope: Local vs Global Variables

Scope determines where a variable can be accessed. This is part of B2.3.4.

Local Variables

A local variable is declared inside a method. It only exists while that method is running and cannot be accessed from any other method.

public class ScopeDemo {
    public static void main(String[] args) {
        int x = 10;           // local to main
        printDouble(x);
        // System.out.println(result);  // ERROR: result does not exist here
    }

    public static void printDouble(int num) {
        int result = num * 2;  // local to printDouble
        System.out.println(result);
        // System.out.println(x);      // ERROR: x does not exist here
    }
}

If you try to use x inside printDouble or result inside main, you get a compile error – the variable is out of scope.

Global (Class-Level) Variables

A global variable (declared with static at the class level) is accessible by all methods in the class.

public class CounterDemo {
    static int count = 0;  // global -- accessible by all methods

    public static void main(String[] args) {
        increment();
        increment();
        increment();
        System.out.println("Count: " + count);  // Count: 3
    }

    public static void increment() {
        count++;  // can access the global variable
    }
}

When to Use Which?

  Local Global (static)
Declared Inside a method Outside methods, at class level
Accessible Only within that method By all methods in the class
Lifetime Created when method starts, destroyed when it ends Exists for the entire program
Preferred? Yes – use by default Only when multiple methods must share state

Prefer local variables and pass data through parameters and return values. Global variables make programs harder to understand and debug because any method can change them at any time. Use them sparingly.


Why Modularize?

Benefit Explanation
Readability calculateAverage(grades) is clearer than 5 lines of arithmetic in the middle of main
Reusability Write once, call many times – no copy-paste
Testing You can test a single method in isolation
Maintainability Change the logic in one place rather than everywhere it appears
Team development Different developers can work on different methods in parallel

IB exams frequently ask students to explain the benefits of modularization. Be ready to name at least three benefits and explain each with an example.


Quick Check

Q1. What is the difference between a parameter and an argument?

Q2. What does void mean in a method header?

Q3. A local variable declared inside a method can be accessed from:

Q4. Which is NOT a benefit of modularization?

Q5. Given public static double calculateAverage(int[] grades), what type of value does this method return?


Trace Exercise

Trace the method calls – fill in the return value and output at each step.

public class TraceMethods {
    public static void main(String[] args) {
        int a = 4;
        int b = 6;
        int sum = add(a, b);
        System.out.println("Sum: " + sum);
        System.out.println("Max: " + findMax(a, b));
        greet("Alice");
    }

    public static int add(int x, int y) {
        return x + y;
    }

    public static int findMax(int x, int y) {
        if (x > y) {
            return x;
        }
        return y;
    }

    public static void greet(String name) {
        System.out.println("Hello, " + name);
    }
}
StepMethod CalledArgumentsReturn ValueOutput
1 add(a, b) 4, 6
2 findMax(a, b) 4, 6
3 greet("Alice") "Alice"

Code Completion

This method calculates the average of an integer array. Complete the missing parts: the return type, the loop condition, and the return statement with the correct cast to avoid integer division.

public static  calculateAverage(int[] grades) {
    int total = 0;
    for (int i = 0; i < ; i++) {
        total = total + grades[i];
    }
    return ;
}

This method takes a String array and a search term, and returns the index where the term is found, or -1 if not found. Complete the return type, the comparison method, and the not-found return value.

public static  searchStudent(String[] names, String target) {
    for (int i = 0; i < names.length; i++) {
        if (names[i].) {
            return i;
        }
    }
    return ;
}

Spot the Bug

This method is supposed to return the maximum value in an array, but the comparison is backwards so it finds the minimum instead. Find the buggy line and pick the correct fix.

This method should return the maximum value in an array, but it returns the minimum instead:

1public static int findMax(int[] arr) { 2 int max = arr[0]; 3 for (int i = 1; i < arr.length; i++) { 4 if (arr[i] < max) { 5 max = arr[i]; 6 } 7 } 8 return max; 9}

Pick the correct fix for line 4:


This method is supposed to count how many even numbers are in an array, but it has a scope error. The variable count is declared inside the loop block, so it does not exist at the return statement. Find the bug.

This method should count even numbers but does not compile:

1public static int countEvens(int[] arr) { 2 for (int i = 0; i < arr.length; i++) { 3 int count = 0; 4 if (arr[i] % 2 == 0) { 5 count++; 6 } 7 } 8 return count; 9}

Pick the correct fix:


Output Prediction

This program demonstrates a method with a return value and a void method working together. Trace the method calls and predict the output.

public class OutputDemo {
    public static void main(String[] args) {
        int x = 3;
        int y = doubleIt(x);
        System.out.println(x + " " + y);
        printStars(y);
    }

    public static int doubleIt(int n) {
        return n * 2;
    }

    public static void printStars(int count) {
        for (int i = 0; i < count; i++) {
            System.out.print("*");
        }
        System.out.println();
    }
}

Type the exact output:


This program shows how local scope works. Each method has its own copy of variables.

public class ScopeOutput {
    public static void main(String[] args) {
        int x = 5;
        change(x);
        System.out.println("main: " + x);
    }

    public static void change(int x) {
        x = x + 10;
        System.out.println("change: " + x);
    }
}

Type the exact output:

Key insight: Passing a primitive value (like int) to a method creates a copy. Changing the copy inside the method does NOT affect the original variable. This is called pass by value. Arrays behave differently – they pass a reference, so changes to array elements inside a method DO affect the original.


Practice Exercises

Core

  1. Print separator – Write a method public static void printSeparator() that prints a line of 30 dashes. Call it from main before and after printing your name.

  2. Sum of two – Write a method public static int sum(int a, int b) that returns the sum of two integers. In main, call it with different values and print the results.

  3. Is even – Write a method public static boolean isEven(int n) that returns true if n is even, false otherwise. In main, test it with several values.

  4. Greeting – Write a method public static void greet(String name) that prints "Hello, [name]! Welcome to CS.". Call it with at least three different names from main.

Extension

  1. Temperature converter – Write two methods:
    • public static double celsiusToFahrenheit(double celsius) – returns the Fahrenheit value
    • public static double fahrenheitToCelsius(double fahrenheit) – returns the Celsius value

    In main, convert and print: 0C, 100C, 32F, 212F.

  2. Array statistics – Write three methods that each take an int[] parameter:
    • public static int findMax(int[] arr) – returns the largest value
    • public static int findMin(int[] arr) – returns the smallest value
    • public static double calculateAverage(int[] arr) – returns the average

    In main, create an array of test grades and call all three methods to print a report.

  3. Password checker – Write a method public static boolean isStrongPassword(String password) that returns true if the password has at least 8 characters, contains at least one digit, and contains at least one uppercase letter. Test it with several passwords from main.

Challenge

  1. Refactor the GradeArray – Take the RefactorGrades.java starter code (everything in main) and fill in the extracted methods:
    • getValidInteger(Scanner input, String message) – validates integer input
    • calculateAverage(int[] grades) – returns the average
    • findMax(int[] grades) – returns the highest grade
    • findMin(int[] grades) – returns the lowest grade
    • printGrades(String[] names, int[] grades) – prints the list
    • searchStudent(String[] names, String searchName) – returns the index or -1

    The main method should read like a high-level summary.

  2. Mini calculator – Build a calculator with these methods:
    • add(double a, double b), subtract(double a, double b), multiply(double a, double b), divide(double a, double b)
    • isValidOperation(String op) – returns true if op is +, -, *, or /
    • Use a loop in main that repeatedly asks for two numbers and an operation, calls the correct method, and prints the result. Exit when the user types "quit" (remember: use .equals() to compare strings, not ==).

GitHub Classroom

Methods & Modularization Exercises
Practice void methods, return methods, array parameters, scope, and methods calling methods. Multiple files -- work on them in class and complete the rest as homework.
Codespace Setup Instructions (click to expand)

First Time Setup

  1. Click “Open in GitHub” above, then click the green “Accept this assignment” button
  2. Check the email registered with your GitHub account – click the link there to open your repository. This avoids access issues and means your teacher does not need to share links manually
  3. Wait for your repository to be created, then click “Open in Codespace”
  4. Wait for the Codespace to finish loading (you’ll see VS Code in your browser)

Important: Switch to Standard Mode

  1. Look at the bottom status bar. If it says Java: Lightweight Mode, click on it and select Standard
  2. Wait for Java to finish loading (status bar will say Java: Ready)
  3. Without Standard Mode, the Run button won’t work and you’ll get “Main method not found” errors

Dismiss Popups

You’ll see two notification popups. Dismiss them both:

  • “Would you like VS Code to periodically run git fetch?” → Click No
  • “There’s a pull request associated with main” → Click Don’t Show Again

These are housekeeping popups, not part of the assignment.

How to Code

  1. Open src/RefactorGrades.java. This is the only file you need to edit
  2. Complete each // TODO sectionStart with RefactorGrades.java (in-class activity), then move to the other files.
  3. Click the Run button (▶ above main) to test your output
  4. Compare your output with the expected output written in the comments above each task

How to Check Your Code

You can check your work in two ways:

Option A: Run your code directly

  • Click the Run button (▶) above main in RefactorGrades.java
  • Compare your printed output with the expected output shown in the comments above each task

Option B: Run the autograder tests

  • Open the Terminal (Menu → Terminal → New Terminal)
  • Type bash run-tests.sh and press Enter
  • Green ✓ = test passed, Red ✗ = test failed
  • Each test tells you what it expected. Read the error message to fix your code

How to Submit

  1. Click the Source Control icon (branch icon) in the left sidebar
  2. Type a message like completed tasks in the message box
  3. Click the green Commit button
  4. If asked “stage all changes?” → click Always
  5. Click Sync Changes → if asked about push/pull → click OK, Don’t Show Again
  6. Done! Autograding runs automatically. Your teacher can see your results in the GitHub Classroom dashboard

How to Review Feedback

  1. Go to your repository on GitHub
  2. Click the “Pull requests” tab at the top
  3. Open the pull request called “Feedback”
  4. Click the “Files changed” tab. You’ll see your teacher’s comments on specific lines of your code
  5. Read through each comment carefully, then fix your code in Codespaces
  6. Run bash run-tests.sh in your Codespaces Terminal to check your fixes
  7. Commit and push again (repeat steps 12-17). The autograder will re-run automatically

Connections

Prerequisites:

Related Topics:

What’s Next:

Methods are the building blocks of everything that comes next. In OOP, methods belong to objects instead of being static. Master methods now and the transition to OOP will feel natural.


© EduCS.me — A resource hub for Computer Science education

This site uses Just the Docs, a documentation theme for Jekyll.