Java Methods
How to Write Them
Learn to define, call, and return values from methods: the fundamental building blocks of organized Java programs.
What Is a Method?
A method is a named block of code that performs a specific task. Instead of writing the same logic over and over, you write it once inside a method and call it whenever you need it.
Why Methods Matter
Anatomy of a Method
The Method Header Explained
void vs. Return Methods
return;).return value; matching the declared type.Parameters vs. Arguments
How to Write a Method: Step by Step
Example 1: A Simple void Method
Notice there is no return statement. The return type is void, so the method simply executes and ends.
Example 2: A Return Method
The return type double tells the compiler: this method promises to send back a decimal number. The formula \( \pi r^2 \) is computed and returned.
Example 3: Boolean Return
This method takes three parameters. The boolean expression is evaluated and its result (true or false) is returned directly: no if-statement needed.
Calling Methods & Using Return Values
Method Overloading
Java allows multiple methods with the same name as long as their parameter lists differ in number or type. This is called overloading.
Scope & Local Variables
Common Mistakes
return statement on some paths. The compiler will error.String where an int is expected. Argument types must match parameter types (or be auto-convertible).add(3, 7); without storing or using the result. The value is computed then discarded.Method Quick Reference
| Feature | void Method | Return Method |
|---|---|---|
| Return type | void | int, double, String, boolean, etc. |
| Return statement | Optional (bare return;) |
Required on all paths |
| Can store result? | No | Yes |
| Example use | Printing, modifying state | Computing, validating, transforming |
| Call syntax | greet("Hi"); |
int x = add(3, 7); |
Question 1 of 5
What is the return type of a method that does not return a value?
Question 2 of 5
Consider the following method:
public static int mystery(int a, int b) {
return a * b + 1;
}
What is the value of mystery(3, 4)?
Question 3 of 5
Which of the following is the correct way to call a static method named average that takes two double parameters and returns a double?
Question 4 of 5
Two methods have the same name but different parameter lists. This is an example of:
Question 5 of 5
Consider the following code:
public static int doubleIt(int n) {
return n * 2;
}
public static void main(String[] args) {
int x = 5;
doubleIt(x);
System.out.println(x);
}
What is printed to the console?
x is copied into n. The method doubles the copy and returns 10, but the return value is never stored. The original x remains 5.