Methods
A method is a block of code used to perform a specific task.
It helps in code reusability.
void greet() {
System.out.println("Hello");
}Important Points
A method cannot be declared inside another method or block
Memory is allocated in Stack Area (Stack Frame)
Memory is created when method is called and destroyed after execution
Method Syntax
<Access Modifier> <Return Type> <Method Name>(Parameters) {
// statements
}1. Access Modifier
Defines scope (where method can be accessed)
publicprivateprotecteddefault
2. Return Type
Defines what type of value method returns
Primitive →
int,float, etc.Object →
String, custom classArray
void→ no return
🔍 Important Rules:
returnstatement sends value back to callerReturn value must match return type
returnshould be last statement
3. Method Name
A valid Java identifier
Used to identify method
4. Parameters
Used to pass input values to method
Optional
Rules for Method Calling:
Argument type must match parameter type
Number of arguments must match
Order must match
Parameter = local variable inside method
class Method {
void m1() {
System.out.println("m1 method");
}
int m2() {
return 10 + 20;
}
float average(float n1, float n2) {
return (n1 + n2) / 2;
}
}
class Main {
public static void main(String[] args) {
Method obj = new Method();
obj.m1();
int result = obj.m2();
System.out.println("Result: " + result);
float avg = obj.average(10.5f, 20.5f);
System.out.println("Average: " + avg);
}
}Types of Methods
1. Instance Method (Non-Static)
Method without
statickeyword
Works on object (late binding)
Must create object to call method
Can access:
Instance variables
Static variables
class A {
int a = 10;
static int b = 20;
void m1() {
System.out.println(a);
System.out.println(b);
}
}
class Main {
public static void main(String[] args) {
A obj = new A();
obj.m1();
}
}Important:
A obj = null;
obj.m1(); // ❌ NullPointerException2. Static Method
Method declared with
statickeyword
Key Points:
Works on class level (early binding)
No need to create object
Can directly access:
Static variables ✅
Instance variables ❌ (need object)
class A {
int a = 10;
static int b = 20;
static void m1() {
System.out.println("Static method");
System.out.println(b);
}
}
class Main {
public static void main(String[] args) {
A.m1();
}
}Ways to Call Static Method
Using class name (Best practice)
A.m1();Using null reference
A a = null;
a.m1();Using object
A a = new A();
a.m1();Method Memory Management
Methods use Stack Memory
Each method gets a stack frame
Stack works on LIFO (Last In First Out)
(Method Chaining):
class A {
void m1() {
System.out.println("Start m1");
m2();
System.out.println("End m1");
}
void m2() {
System.out.println("Start m2");
m3();
System.out.println("End m2");
}
void m3() {
System.out.println("m3 method");
}
}
class Main {
public static void main(String[] args) {
new A().m1();
}
}Output:
Start m1
Start m2
m3 method
End m2
End m1Execution Flow:
main()→ callsm1()m1()→ callsm2()m2()→ callsm3()Stack follows LIFO order