Methods & Modularization
IB Syllabus: B2.3.4 - Construct functions and modularization.
Table of Contents
- Key Concepts
- Worked Examples
- Scope: Local vs Global Variables
- Why Modularize?
- Quick Check
- Trace Exercise
- Code Completion
- Spot the Bug
- Output Prediction
- Practice Exercises
- GitHub Classroom
- 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 frommain. 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 arguments5and3to parametersaandb. The method computesa + band returns8.- The returned value can be stored in a variable (
result) or used directly insideprintln.
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:
maincallsprintReport, which callsprintSeparator,printGrades, andcalculateAverage.- Each method has a single, clear job.
mainreads like a high-level summary of the program. calculateAveragereturns adoublethatprintReportstores and prints.
Try it: Look at the
MiniProjcode 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);
}
}
| Step | Method Called | Arguments | Return Value | Output |
|---|---|---|---|---|
| 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:
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:
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
-
Print separator – Write a method
public static void printSeparator()that prints a line of 30 dashes. Call it frommainbefore and after printing your name. -
Sum of two – Write a method
public static int sum(int a, int b)that returns the sum of two integers. Inmain, call it with different values and print the results. -
Is even – Write a method
public static boolean isEven(int n)that returnstrueifnis even,falseotherwise. Inmain, test it with several values. -
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 frommain.
Extension
- Temperature converter – Write two methods:
public static double celsiusToFahrenheit(double celsius)– returns the Fahrenheit valuepublic static double fahrenheitToCelsius(double fahrenheit)– returns the Celsius value
In
main, convert and print: 0C, 100C, 32F, 212F. - Array statistics – Write three methods that each take an
int[]parameter:public static int findMax(int[] arr)– returns the largest valuepublic static int findMin(int[] arr)– returns the smallest valuepublic 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. - Password checker – Write a method
public static boolean isStrongPassword(String password)that returnstrueif the password has at least 8 characters, contains at least one digit, and contains at least one uppercase letter. Test it with several passwords frommain.
Challenge
- Refactor the GradeArray – Take the
RefactorGrades.javastarter code (everything inmain) and fill in the extracted methods:getValidInteger(Scanner input, String message)– validates integer inputcalculateAverage(int[] grades)– returns the averagefindMax(int[] grades)– returns the highest gradefindMin(int[] grades)– returns the lowest gradeprintGrades(String[] names, int[] grades)– prints the listsearchStudent(String[] names, String searchName)– returns the index or -1
The
mainmethod should read like a high-level summary. - 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
mainthat 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
Codespace Setup Instructions (click to expand)
First Time Setup
- Click “Open in GitHub” above, then click the green “Accept this assignment” button
- 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
- Wait for your repository to be created, then click “Open in Codespace”
- Wait for the Codespace to finish loading (you’ll see VS Code in your browser)
Important: Switch to Standard Mode
- Look at the bottom status bar. If it says
Java: Lightweight Mode, click on it and select Standard - Wait for Java to finish loading (status bar will say
Java: Ready) - 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
- Open
src/RefactorGrades.java. This is the only file you need to edit - Complete each
// TODOsectionStart with RefactorGrades.java (in-class activity), then move to the other files. - Click the Run button (▶ above
main) to test your output - 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
maininRefactorGrades.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.shand 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
- Click the Source Control icon (branch icon) in the left sidebar
- Type a message like
completed tasksin the message box - Click the green Commit button
- If asked “stage all changes?” → click Always
- Click Sync Changes → if asked about push/pull → click OK, Don’t Show Again
- Done! Autograding runs automatically. Your teacher can see your results in the GitHub Classroom dashboard
How to Review Feedback
- Go to your repository on GitHub
- Click the “Pull requests” tab at the top
- Open the pull request called “Feedback”
- Click the “Files changed” tab. You’ll see your teacher’s comments on specific lines of your code
- Read through each comment carefully, then fix your code in Codespaces
- Run
bash run-tests.shin your Codespaces Terminal to check your fixes - Commit and push again (repeat steps 12-17). The autograder will re-run automatically
Connections
Prerequisites:
- Selection (if/else) – conditions used in method logic
- Iteration (Loops) – loops used inside methods
- 1D Arrays – arrays passed as method parameters
Related Topics:
- Searching Algorithms – linear and binary search are methods
- Sorting Algorithms – selection sort as a method
What’s Next:
- OOP: Classes & Objects – methods become part of objects
- OOP: Encapsulation – access modifiers control method visibility
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.