Functions
In Java, functions are called methods because they always live inside a class. Like C++, Java supports method overloading — multiple methods sharing a name but differing in parameters.
💡 Key insight
In Java, every method belongs to a class — there's no such thing as a truly standalone function like in C.
Syntax
syntax
returnType methodName(type param) {
return value;
}Example
static means add belongs to the class itself, so main (also static) can call it directly without creating an object.
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);
}
}outputSum: 11
Try it yourself
Copy this example into the Java compiler and run it — try changing a value and see what happens.
