Background
Today I was going through a Reddit post. I got confused about
Is the "method" & the "function" are same? If not, then what's the difference?
Even after 8 years of learning and writing code, this question has left me uncertain and confused.
My findings!
A big NO - a method and a function are not the same thing.
Method
A method is a piece of code that performs a specific task and is associated with an object. You can call the (invoke) method using a reference variable of an object.
public class Math {
private int firstNumber;
private int secondNumber;
public Math(int firstNumber, int secondNumber) {
this.firstNumber = firstNumber;
this.secondNumber = secondNumber;
}
public int addition() {
return firstNumber + secondNumber;
}
}
In this example, the "add" method is associated with an instance of the "Math" class, like this :
Math math = new Math(77, 94);
int result = math.addition();
Function
Whereas, a function is a piece of code that performs a specific task and can be called (invoked) by code outside of it. You can pass on some parameter(s) as input and get the results in return.
In Java, a function is defined using the "static" keyword, like this:
public static int addition(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
Conclusion
The methods belong to objects and can modify the state of an object. While functions do not have this capability. You can call the functions without creating an object of the class.
Happy Learning!