A method in Java is a block of code that performs a specific task.
void greet() {
System.out.println("Hello!");
}A method usually has:
- a return type
- a name
- parameters (optional)
- a body
returnType methodName(parameters) {
// code
}You must create an object to call them.
class Test {
void show() {
System.out.println("Instance Method");
}
}
Test obj = new Test();
obj.show();Can be called without creating an object — using class name.
class Test {
static void display() {
System.out.println("Static Method");
}
}
Test.display();Methods with input parameters.
void sum(int a, int b) {
System.out.println(a + b);
}Methods that return a value.
int add(int a, int b) {
return a + b;
}| Feature | Function | Method |
|---|---|---|
| Belongs to | Independent (not inside a class) | Always inside a class |
| Used in | C, C++, Python | Java |
| Relation with object | Not related to objects | Related to classes/objects |
| Example | int add() {} in C |
void show() in Java class |
👉 Function = general term
👉 Method = function inside a class
Because Java is 100% object-oriented, every function exists inside a class, so they are called methods.
int add(int a, int b) {
return a + b;
}class Demo {
int add(int a, int b) {
return a + b;
}
}