Java • Functions and Program Structure

Defining Methods — Define methods with parameters and return types

Learn to write reusable blocks of code that accept input, perform tasks, and return results.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 6 figures

SECTION 1

Historical Context & Motivation

Imagine you had to write the same 20 lines of code every time you wanted to calculate a student's grade average. Without methods, early programmers faced exactly that problem — massive blocks of repetitive code that were hard to read, debug, and maintain. The idea of breaking a program into smaller, reusable pieces has been central to computer science since its earliest days.

The concept of a subroutine — a named block of code you can call repeatedly — dates back to the 1940s and 1950s. As programming languages evolved, this idea was refined into what Java calls methods. Methods allow you to organize your code, eliminate repetition, and build programs that are easier to understand and extend.

1949 • Subroutines Emerge

Mathematician John Mauchly introduces the concept of reusable subroutines in early computing, allowing code to be called from multiple places in a program.

1967 • Simula & Object-Oriented Thinking

The Simula language introduces classes and methods as part of object-oriented programming, grouping data with the functions that operate on it.

1972 • C Language Functions

Dennis Ritchie creates C, which popularizes functions with parameters and return types — the direct ancestor of Java's method syntax.

1995 • Java is Released

James Gosling and Sun Microsystems release Java, adopting methods as the fundamental unit of behavior inside classes, with strict type enforcement for parameters and return values.

So the question driving this lesson is straightforward: how do you define a method in Java that accepts specific inputs and produces a specific output? Mastering this skill is the foundation for writing clean, modular, and professional code.

SECTION 2

Core Principles & Definitions

A method in Java is a named block of code that performs a specific task. Every method lives inside a class, and you can call it whenever you need that task performed. To define a method properly, you need to understand four key concepts: the return type, the method name, parameters, and the method body.

1

Return Type

The data type of the value the method sends back to the caller. Use void if the method returns nothing, or types like int, double, or String if it does.
2

Method Name

A descriptive identifier following camelCase convention (e.g., calculateAverage). The name should clearly describe what the method does.
3

Parameters

Variables listed in the parentheses of the method header. Each parameter has a type and a name (e.g., int score). Parameters act as inputs that the method uses to do its work.
4

Method Body

The code between the curly braces { } that executes when the method is called. If the method has a return type (not void), the body must include a return statement.
5

Access Modifier

Keywords like public, private, or static that control who can call the method and how it is accessed. For now, most of your methods will be public static.
✦

KEY TAKEAWAY

Think of a method like a vending machine. You put in specific items (parameters), the machine does its work internally (method body), and it gives you back a specific product (return value). A void method is like a machine that does something — say, plays a song — but doesn't hand you a physical object back.

SECTION 3

Anatomy of a Method Definition

The diagram below breaks down the structure of a Java method definition. Every method you write follows this exact pattern, so it's worth studying each labeled part carefully.

Anatomy of a Java Methodpublic static int addNumbers(int a, int b) { int sum = a + b; return sum;}AccessModifierstaticKeywordReturnTypeMethodNameParameters(type name, ...)METHOD BODYThe logic that runs when the method is called.RETURN STATEMENTSends a value back to the caller. Requiredfor non-void methods.
Each part of the method header serves a specific purpose. The return type (here, int) tells Java what kind of value the method will send back. The parameters (int a, int b) define the inputs the method expects.

Notice how every part of the method signature appears before the opening curly brace. The compiler reads this header to know what the method is called, what data it needs, and what data type it promises to return. Inside the body, the return statement fulfills that promise by sending a value of the declared type back to whoever called the method.

SECTION 4

How Methods Work — Parameters & Return Flow

The Method Signature

The method signature is the combination of the method name and its parameter list. Java uses the signature to distinguish one method from another. Two methods can share the same name as long as their parameter lists differ — this is called method overloading, which you'll explore in a future lesson.

GENERAL METHOD SYNTAX

accessModifierreturnTypemethodName(type1param1,type2param2,…)bodyaccessModifier returnType methodName(type₁ param₁, type₂ param₂, …) { body }

accessModifier → public, private, etc. | returnType → any data type or void | param₁, param₂ → local variables that receive argument values

Parameters vs. Arguments

A common source of confusion is the difference between parameters and arguments. Parameters are the variables declared in the method header — they are placeholders. Arguments are the actual values you pass in when you call the method. For example, in the definition int addNumbers(int a, int b), a and b are parameters. When you call addNumbers(5, 3), the values 5 and 3 are arguments.

The return Statement

When a method has a return type other than void, it must include a return statement that provides a value matching the declared type. Once return executes, the method immediately stops, and the returned value can be stored in a variable or used in an expression by the caller. A void method may optionally use return; (with no value) to exit early, but it is not required.

⚠

Common Mistake

If your method declares a return type of int but you forget the return statement, the compiler will give you an error: "missing return statement." Every code path through a non-void method must return a value.

SECTION 5

Classification — void vs. Value-Returning Methods

Methods in Java fall into two broad categories based on whether they return a value. Understanding the difference helps you choose the right structure for the task at hand.

void Methods vs. Value-Returning Methodsvoid MethodPerforms an action, returns nothingpublic static void greet( String name) { System.out.println( "Hello, " + name);}→No return valueUse when the goal is a sideeffect: printing, modifying dataValue-Returning MethodComputes and returns a resultpublic static double average(int a, int b){ return (a + b) / 2.0;}→double resultUse when you need the answerfor further computation
A void method performs an action like printing, while a value-returning method computes and sends back a result that can be stored or used in expressions.
Featurevoid MethodValue-Returning Method
Return type keywordvoidAny type: int, double, String, etc.
return statementOptional (no value)Required (must return matching type)
Can be used in an expression?No — cannot assign to a variableYes — can be stored, printed, or used in math
Typical useDisplay output, modify external stateCompute a result for the caller to use

Comparison of void and value-returning methods

SECTION 6

Worked Example — Building a Grade Calculator Method

Let's walk through building a method from scratch. Suppose you're writing a program that calculates a letter grade from a numeric test score. You want a method that takes the score as input and returns the letter grade as a String.

Defining a getLetterGrade Method

  1. 1

    Step 1 — Identify the Return Type

    The method needs to return a letter grade like "A" or "B". Since these are text values, the return type should be String. We write the header start: public static String
    Return type: String
  2. 2

    Step 2 — Choose the Method Name

    The name should describe what the method does. Following Java's camelCase convention, we choose getLetterGrade. Descriptive names make your code self-documenting.
    Name: getLetterGrade
  3. 3

    Step 3 — Define the Parameters

    The method needs one piece of input — the numeric score. Since test scores can be whole numbers, we use int score as the parameter. The full header now reads: public static String getLetterGrade(int score)
    Parameter: int score
  4. 4

    Step 4 — Write the Method Body

    Inside the curly braces, we use if-else statements to determine the grade. Each branch returns the appropriate String. Here is the complete method: public static String getLetterGrade(int score) { if (score >= 90) { return "A"; } else if (score >= 80) { return "B"; } else if (score >= 70) { return "C"; } else if (score >= 60) { return "D"; } else { return "F"; } }
    Every path through the if-else chain returns a String — no missing return statements.
  5. 5

    Step 5 — Call the Method

    In your main method, you call it like this: String grade = getLetterGrade(85);. The argument 85 is copied into the parameter score. Since 85 ≥ 80, the method returns "B", which is stored in the variable grade.
    grade now holds the value "B"

SECTION 7

Strengths, Pitfalls & Best Practices

Defining methods well is both a skill and an art. Here are common strengths and pitfalls to be aware of as you start writing your own methods.

Best PracticeCommon Pitfall
Use descriptive method names: calculateArea tells the reader what happens.Vague names like doStuff or x make code unreadable.
Each method should do one thing. This makes debugging and testing easier.Writing a single method that does five unrelated tasks creates tangled, fragile code.
Match the return type to how the result will be used. If you need decimal precision, use double.Using int when you need decimals causes silent truncation: 5 / 2 yields 2, not 2.5.
Keep the parameter list short (1–4 parameters). More than that suggests the method is trying to do too much.Passing 8+ parameters makes method calls confusing and error-prone.
Always ensure every branch returns a value in non-void methods.Forgetting a return in an else branch causes a compile error.

Best practices vs. common pitfalls when defining methods

💡

DESIGN PRINCIPLE

A well-designed method is like a well-labeled tool in a toolbox — you pick it up, you know exactly what it does, you use it, and you put it back. If your method name reads like a verb phrase ("calculateTax", "isEven", "printReport"), you're on the right track.

SECTION 8

Connection to Advanced Topics

The methods you're learning to define right now are the building blocks for more advanced Java programming. As you progress, you'll encounter methods that interact with objects, methods that call themselves, and methods that implement abstract interfaces. Here's a preview of how today's skills connect to what's ahead.

What You Know NowWhat Comes Next
static methods that belong to the classInstance methods that operate on object data (no static keyword)
Methods with unique namesMethod overloading — same name, different parameter lists
Calling other methodsRecursion — a method calling itself to solve smaller sub-problems
Returning primitive types and StringsReturning objects and arrays — methods that return complex data structures

How today's concepts lead to advanced Java topics

Every advanced feature builds on the basic pattern you've learned today: define a return type, name the method, list the parameters, write the body, and return a result. If you understand this pattern deeply, the more complex topics will feel like natural extensions rather than entirely new concepts.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

What is the difference between a parameter and an argument in Java? Give an example of each.
Show answer
A parameter is a variable declared in the method header that acts as a placeholder for incoming data. An argument is the actual value passed to the method when it is called. For example, in public static int square(int n), n is the parameter. When you call square(7), the value 7 is the argument. The argument's value is copied into the parameter when the method executes.

Question 2: BASIC CALCULATION

Write a method called multiply that takes two int parameters and returns their product as an int. Then show how you would call it with the values 6 and 4.
Show answer
The method definition is: public static int multiply(int a, int b) { return a * b; }. The return type is int because the product of two integers is an integer. To call it: int result = multiply(6, 4);. After this line, result holds the value 24.

Question 3: INTERMEDIATE

Write a method called isEven that takes an int parameter and returns a boolean — true if the number is even, false otherwise. Explain why boolean is the correct return type.
Show answer
The method: public static boolean isEven(int num) { return num % 2 == 0; }. The boolean return type is correct because the question "Is this number even?" has only two possible answers: yes (true) or no (false). The expression num % 2 == 0 evaluates to a boolean directly, so we can return it without needing an if-else.

Question 4: APPLIED

You are building a tip calculator app. Write a method called calculateTip that takes two parameters — the bill amount as a double and the tip percentage as an int — and returns the tip amount as a double. What would the method return for a $45.00 bill with a 20% tip?
Show answer
The method: public static double calculateTip(double bill, int tipPercent) { return bill * tipPercent / 100.0; }. We use double as the return type because tip amounts usually involve decimals. Dividing by 100.0 (not 100) ensures floating-point division. Calling calculateTip(45.0, 20) computes 45.0 × 20 / 100.0 = 9.0, so the method returns 9.0.

Question 5: CRITICAL THINKING

A student writes the following method, but it won't compile. Identify ALL of the errors and explain how to fix each one: public static int getMax(int a, b) { if (a > b) { return a; } }
Show answer
There are two errors. First, the parameter b is missing its type declaration. In Java, every parameter must have its own type explicitly stated, so it should be int a, int b. Second, the method declares a return type of int but only returns a value when a > b. If a <= b, no return statement is reached, which causes a "missing return statement" error. The fix is to add an else { return b; } block so that every code path produces a return value.

SUMMARY

Summary

Summary

A method in Java is a named, reusable block of code defined inside a class. Every method definition includes an access modifier, a return type (which is void when no value is returned), a descriptive method name in camelCase, and a list of parameters (each with a declared type). The method body contains the logic, and non-void methods must include a return statement on every possible execution path.

Remember the distinction: parameters are the placeholders in the method definition, while arguments are the actual values passed during a method call. void methods perform actions without returning a value, while value-returning methods compute and send back a result. Mastering method definitions is the foundation for writing clean, modular Java programs and prepares you for object-oriented programming, method overloading, and recursion.

Varsity Tutors • Java • Defining Methods — Define methods with parameters and return types