Skip to content
C

Methods

A method is a named block of code inside a class that performs a specific task. Methods let you group a set of instructions together so they can be reused by simply calling the method's name.


1. What is a Method?

A method is a named block of code inside a class that performs a specific task. Methods let you group a set of instructions together so they can be reused by simply calling the method's name.

2. Why is it used?

Without methods, you would have to rewrite the same logic every time you need it. Methods let you write logic once — like calculating an average — and reuse it as many times as needed, just by calling it.

3. Real-Life Example

Think of a coffee machine with a single "Make Coffee" button. Pressing that one button triggers a whole series of internal steps (grinding, brewing, pouring), without you needing to perform each step manually every time.

4. Syntax

java
returnType methodName(parameters) { // method body }

5. Example Program

java
public class MethodDemo { static int addNumbers(int a, int b) { return a + b; } public static void main(String[] args) { int result = addNumbers(10, 20); System.out.println("Sum: " + result); } }

Output:

Sum: 30

6. Key Points to Remember

  • A method's return type must match the type of value it actually returns (or be void if it returns nothing).
  • Method names should clearly describe what the method does.
  • Parameters let a method receive different input values each time it's called.