Unit 2 · Java Fundamentals · 9 min
Methods
A method is a named block of code that does one job. You write it once and call it whenever you need it.
Why this matters
Methods stop repetition, make programs readable, and are the direct stepping stone to classes and objects.
Real-life analogy
A method is like a kitchen appliance. You put ingredients in (parameters), it does its job, and it hands you a result (return value).
Syntax
Syntax
returnType methodName(parameters) {
// body
return value; // not needed when returnType is void
}Example
Java
public class Calc {
static int add(int a, int b) {
return a + b;
}
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
int sum = add(12, 8);
System.out.println("Sum = " + sum);
greet("Ananya Rao");
}
}Output
Sum = 20 Hello, Ananya Rao!
Step by step
- 1`static int add(int a, int b)` declares a method that takes two ints and returns an int.
- 2`return a + b;` sends the answer back to whoever called the method.
- 3`void greet(String name)` returns nothing; it only prints.
- 4`add(12, 8)` is the call. 12 and 8 are arguments; a and b are parameters.
- 5Methods are marked static here so main can call them without creating an object.
Key points
- Parameters are inputs, return value is the output
- void means the method returns nothing
- A method should ideally do one clear job
- Calling a method runs its body and then comes back to where you were
Common mistakes
- Forgetting to return a value in a non-void method
- Calling a non-static method directly from main without an object
- Passing arguments in the wrong order
Try it yourself
- Write a method isEven(int n) that returns true or false.
- Write a method that returns the largest of three numbers.