Java Methods and Functions
A method is a reusable block of code that performs a specific task. Methods are also called functions. Organizing code into methods improves code readability, maintainability, and enables code reuse.
What is a Method?
In object-oriented programming, methods define the behaviors of objects. For example, a Calculator object might have an add() method to perform addition operations.
Defining Methods
A complete method definition includes:
- Modifier: Such as
public,static.publicmeans the method can be accessed by any class.staticmeans the method belongs to the class itself, not to any specific object of the class. - Return Type: The type of data returned after the method finishes executing. If the method doesn't return any value, use
void. - Method Name: The name of the method, following camelCase naming convention.
- Parameter List: A list of variables declared within parentheses to receive values passed to the method when called. If the method doesn't need parameters, the parentheses are left empty.
- Method Body: The specific code contained within curly braces
{}.
Syntax:
modifier returnType methodName(parameter1Type parameter1Name, ...) {
// Method body
// ...
return value; // If return type is not void
}Example:
public class Calculator {
// Define an addition method
// public: modifier
// int: return type
// add: method name
// (int a, int b): parameter list
public int add(int a, int b) {
int sum = a + b;
return sum; // Return the calculation result
}
// Define a method that returns no value
public void printWelcomeMessage() {
System.out.println("Welcome to the calculator!");
}
}Calling Methods
To execute a method, you need to "call" it.
- If it's an instance method (no
statickeyword), you need to create an object of the class first, then call through the object. - If it's a static method (has
statickeyword), you can call it directly through the class name.
public class Main {
public static void main(String[] args) {
// Calling instance methods
Calculator myCalculator = new Calculator(); // Create object
myCalculator.printWelcomeMessage(); // Call void method through object
int result = myCalculator.add(10, 20); // Call method with return value
System.out.println("10 + 20 = " + result); // Output: 30
// Calling static methods (e.g., Math.max)
int maxNumber = Math.max(5, 8); // Call directly through class name
System.out.println("Maximum is: " + maxNumber);
}
}Parameters vs. Arguments
- Parameter: Variables declared in the method definition, such as
aandbinadd(int a, int b). - Argument: The actual values passed to the method when calling it, such as
10and20inmyCalculator.add(10, 20).
Method Overloading
Method overloading allows defining multiple methods with the same name in a class, as long as their parameter lists are different (different in number, type, or order of parameters). The compiler decides which version of the method to call based on the arguments you pass.
public class Greeter {
public void sayHello() {
System.out.println("Hello!");
}
public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
public void sayHello(String name, int times) {
for (int i = 0; i < times; i++) {
System.out.println("Hello, " + name + "!");
}
}
}The static Keyword
- Static method (
staticmethod): Belongs to the class itself, not dependent on any object instance. Can be called directly through the class name. Themainmethod is a typical static method. - Instance method: Belongs to objects of the class. Must be called through a class instance. It can access the object's instance variables.
Java's Pass-by-Value
This is a very important concept: Java always passes arguments by value.
For primitive types: The method receives a copy of the argument value. Modifying the parameter inside the method does not affect the original argument variable.
javapublic void changeValue(int x) { x = 20; // Modifies the copy x } int original = 10; changeValue(original); // Passes a copy of the value 10 // original is still 10For reference types (objects): The method receives a copy of the object reference. This copy and the original reference point to the same object in heap memory. Therefore, if you modify the object's state (i.e., the object's instance variables) through this reference copy inside the method, the modification will be reflected in the original object. However, if you make the parameter reference point to a new object inside the method, the original reference will not be affected.
javaclass MyData { int value; } public void changeObject(MyData data) { data.value = 99; // Modifies the same object in heap } MyData myData = new MyData(); myData.value = 1; changeObject(myData); // Passes a copy of the reference, but points to the same object // myData.value is now 99