Loading content...
Loading content...
A method is a block of code used to perform a specific task.
It helps in code reusability.
java
void greet() {
System.out.println("Hello");
}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
java
<Access Modifier> <Return Type> <Method Name>(Parameters) {
// statements
}Defines scope (where method can be accessed)
public
private
protected
default
Defines what type of value method returns
Primitive → int, float, etc.
Object → String, custom class
Array
void → no return
return statement sends value back to caller
Return value must match return type
return should be last statement
A valid Java identifier
Used to identify method
Used to pass input values to method
Optional
Argument type must match parameter type
Number of arguments must match
Order must match
Parameter = local variable inside method
java
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);
}
}Method without static keyword
Works on object (late binding)
Must create object to call method
Can access:
Instance variables
Static variables
java
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();
}
}java
A obj = null;
obj.m1(); // ❌ NullPointerExceptionMethod declared with static keyword
Works on class level (early binding)
No need to create object
Can directly access:
Static variables ✅
Instance variables ❌ (need object)
java
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();
}
}Using class name (Best practice)
java
A.m1();Using null reference
java
A a = null;
a.m1();Using object
java
A a = new A();
a.m1();Methods use Stack Memory
Each method gets a stack frame
Stack works on LIFO (Last In First Out)
plaintext
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();
}
}java
Start m1
Start m2
m3 method
End m2
End m1main() → calls m1()
m1() → calls m2()
m2() → calls m3()
Stack follows LIFO order