Methods in Java: Static and Instance Methods Explained with Examples
Methods in Java
A method in Java is a block of statements that is used to perform a specific task and may return a result.
Methods help improve code reusability, readability, and modular programming.
Java methods are mainly classified into two types:
- Static Method
- Instance Method
1. Static Method
✅ Definition
A static method is a method that is declared using the static keyword inside a class.
It belongs to the class, not to any specific object.
Static methods are generally used to perform common operations that are the same for all users.
🔹 Syntax
static returnType methodName() {
// method body
}
🌍 Real-Life Example
ATM Bank Interest Rate
Interest calculation formula is the same for all customers
So it can be implemented as a static method
🧠 Example Code
class Calculator {
static int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
int result = Calculator.add(10, 20);
System.out.println(result);
}
}
📌 Key Points of Static Methods
- Called using class name
- No object creation required
- Can directly access static variables
- Cannot directly access instance members
2. Instance Method
✅ Definition
An instance method is a method that is declared without the static keyword.
It belongs to an object of the class.
Instance methods are used to perform user-specific operations.
🔹 Syntax
returnType methodName() {
// method body
}
🌍 Real-Life Example
Student Report Card
Each student has different marks
So marks calculation is done using instance methods
🧠 Example Code
class Student {
int marks;
void displayMarks() {
System.out.println(marks);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.marks = 85;
s1.displayMarks();
}
}
📌 Key Points of Instance Methods
- Called using object reference
- Object creation is mandatory
- Can access both static and instance variables
- Different objects can produce different results
Comments
Post a Comment