Meethod Functionality
Java methods serve multiple purposes in object-oriented programming:
- Code Reuse: Encapsulate logic for repeated execution without duplication
- Modularization: Break complex tasks into manageable units
- Encapsulation: Control access to class data through defined interfaces
- Readability: Descriptive names clarify functionality
- Polymorphism: Enable method overriding and overloading
- Exception Handling: Declare potential errors for callers to handle
- Recursion: Solve problems through self-invocation
Method Definition
A Java method declaration includes:
- Access modifier (
public,protected,private) - Return type (
voidfor no return) - Method name (camelCase convention)
- Parameter list (type and name pairs)
- Method body (execution logic)
public class MathOperations {
public int computeSum(int first, int second) {
int result = first + second;
return result;
}
public void showOutput(String text) {
System.out.println(text);
}
}
Parameters and Arguments
Key distinctions in method invocation:
- Formal Parameters: Variables declared in method signature
- Actual Arguments: Values passed during method calls
- Passing Mecahnisms:
- Primitive types: Passsed by value (copies)
- Objects: References passed by value
public class ParameterDemo {
public static void main(String[] args) {
int base = 5;
modifyPrimitive(base); // Original unchanged
DataHolder holder = new DataHolder();
holder.value = 10;
modifyReference(holder); // Original modified
}
static void modifyPrimitive(int num) {
num = 15;
}
static void modifyReference(DataHolder ref) {
ref.value = 20;
}
}
class DataHolder {
int value;
}
JVM Memory Structure
Key memory areas in Java Virtual Machine:
| Area | Purpose |
|---|---|
| Heap | Object storage, garbage collection focus |
| Method Area | Class metadata, static variables |
| Stack | Method frames, local variables |
| Program Counter | Thread execution position |
| Native Stack | Non-Java method support |
Method Overloading
Technique for defining multiple methods with same name but different signatures:
- Requires distinct parameter types, counts, or orders
- Return type doesn't differentiate overloads
- Access modifiers and exceptions can vary
public class DisplayService {
public void render(int number) {
System.out.println("Integer: " + number);
}
public void render(double value) {
System.out.println("Double: " + value);
}
public void render(String text) {
System.out.println("Text: " + text);
}
public void render(int x, int y) {
System.out.println("Coordinates: (" + x + "," + y + ")");
}
}