Definition
📌 Functions
In Java, functions are called methods because they always live inside a class.
Syntax
syntax
returnType methodName(type param) {
return value;
}Example
java
public class Main {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(4, 7);
System.out.println("Sum: " + result);
}
}Output
outputSum: 11
Important Points
- Methods are declared inside a class — there are no free-floating functions in Java.
staticmethods belong to the class; instance methods belong to individual objects.- Java supports method overloading: same name, different parameter lists.
- Java arguments are passed by value, but for objects, the value passed is a reference to the object.
Common Mistakes
- Trying to call a non-static method directly from
mainwithout creating an object first. - Overloading methods that differ only by return type — Java doesn't allow this.
- Confusing "pass by value" for objects with "pass by reference" — Java passes object references by value.
Interview Tip
🎯 Before your interview
Be ready to explain Java's "pass by value" rule precisely: for objects, it's the reference itself that's copied, not the object's contents.
