intdoubleStringintJust like constructors, methods can also be overloaded.
int add(int x, int y) {}
double add(double x, double y) {} // Overloading because parameter data types are different
Example:
getName() // gets the name of an object
setName() // sets the name of an object
There are two ways to pass arrays as parameters to a method:
int sum(int[] arr) {
int ret = 0;
for (int i : arr) {
ret += i;
}
return ret;
}
int sum(int ... arr) {
int ret = 0;
for (int i : arr) {
ret += i;
}
return ret;
}
Note: Use a deep copy buffer to prevent changes to the original variable in call by reference.
The returned value must match the method’s declared return type.
Example:
String add(String a, String b) {
return a + b; // Returns a concatenated string
}
Alternatively, the return value should be convertible to the function’s return type:
int add(byte a, byte b) {
return a + b; // When bytes undergo arithmetic operations, they are automatically converted to int
}
return statement only to exit early—for instance, in recursive functions to prevent infinite loops.It is important to declare the same method with different parameters to handle various situations flexibly.