Instructor:
Nauman
Khan
INTRODUCTION
TO FUNCTION
INTRODUCTION
• A method is a block of code that
performs a specific task.
• Helps in reusability, readability,
and modular programming.
• Defined once, used multiple
times.
METHOD SYNTAX
returnType methodName(parameters) {
// body
return value; // if return type is not void
}
• returnType → data type of value returned
(int, String, void, etc.)
• methodName → identifier for the method
• parameters → input values (optional)
CLASSIFICATION OF
METHODS
There are 4 types of methods in
Java:
1. Without Parameters, Without
Return
2. Without Parameters, With
Return
3. With Parameters, Without
Return
4. With Parameters, With Return
EXAMPLE 1: WITHOUT
PARAMETERS, WITH
RETURN
int getNumber() {
return 42;
}
main() → calls getNumber() and prints 42.
EXAMPLE 2: WITH
PARAMETERS,
WITHOUT RETURN
void printSum(int a, int b) {
[Link]("Sum = " + (a + b));
}
main() → [Link](10, 20);
EXAMPLE 3: WITH
PARAMETERS, WITH
RETURN
int multiply(int a, int b) {
return a * b;
}
main() → calls multiply(5, 6) and prints 30.
EXAMPLE 4: WITHOUT
PARAMETERS,
WITHOUT RETURN
void displayMessage() {
[Link]("Hello, welcome to Java
methods!");
}
main() → [Link]();
WHY USE METHODS?
• CODE • CODE • EASIER • LOGICAL
REUSABILITY READABILITY TESTING & MODULARITY
& DEBUGGING
MAINTAINABILI
TY
REAL-WORLD ANALOGY
• Methods are like kitchen appliances:
- Blender → Takes input (fruit), returns output (juice).
- Light Switch → No input, no return (just performs
action).
Methods are like appliances or tools –
they take input, perform an action, and
METHO may return output.
DS AS 🍹 Blender → input fruit → output juice
REAL- 💡 Light Switch → no input → just action
LIFE 🏧 ATM → input PIN & amount → output
cash
ACTION 📸 Camera → click button → output
photo
S 🔔 Doorbell → button press → rings
sound
METHODS IN JAVA
(EXAMPLES)
Every analogy maps to a Java method:
class Demo {
// Blender → method with input + return
int add(int a, int b) {
return a + b;
}
// Light Switch → void method (no return)
void turnOnLight() {
[Link]("Light is ON");
}
// Doorbell → void method (just action)
void ringBell() {
[Link]("Ding Dong!");
}
SUMMARY
• Methods are essential for structured programming.
• Four main types:
1. No Param, No Return
2. No Param, With Return
3. With Param, No Return
4. With Param, With Return
• Practice by writing simple utility methods (sum, greeting,
table, random).