- Method Fundamentals
1.1 What Is a Method?
A method is a self-contained block of code that performs a specific task, grouped together as a single unit with special functionality. Methods enable code reuse, improve organization, and make programs more maintainable.
Key Points:
- Methods must be defined before they can be used—this process is called method definition.
- After definition, methods don't execute automatically; they require explicit invocation—this process is called method call.
- Defining and Invoking Methods
2.1 Parameterless Methods
Definition Syntax:
public static void methodName() {
// method body
}
Example:
public static void displayMessage() {
System.out.println("Hello from method!");
}
Invocation Syntax:
methodName();
Example:
displayMessage();
Important: Methods must be defined before they are called; otherwise, the compiler will throw an error.
2.2 Method Execution Flow
When a method is invoked, it enters the JVM stack memory and obtains its own独立的内存空间 (independent memory space). Once the method's code completes execution, it pops off the stack and the memory is released.
2.3 Practical Example: Odd-Even Number Checker
Requirement: Determine whether a given number is odd or even.
public class OddEvenChecker {
public static void main(String[] args) {
evaluateNumber(15);
}
public static void evaluateNumber(int value) {
if (value % 2 == 0) {
System.out.println(value + " is even");
} else {
System.out.println(value + " is odd");
}
}
}
- Methods with Parameters
3.1 Defining Parameterized Methods
Parameters consist of a data type and variable name: dataType variableName.
Single Parameter:
public static void methodName(parameter1) {
methodBody;
}
Multiple Parameters:
public static void methodName(parameter1, parameter2, parameter3...) {
methodBody;
}
Examples:
public static void checkEvenNumber(int number) {
// implementation
}
public static void findMaximum(int first, int second) {
// implementation
}
Critical Notes:
- Both the data type and variable name are required when defining parameters.
- Multiple parameters must be separated by commas.
3.2 Invoking Parameterized Methods
Syntax:
methodName(parameter);
methodName(parameter1, parameter2);
Examples:
checkEvenNumber(25);
findMaximum(50, 100);
Important: The number and types of arguments must match the method's parameter declaration exactly.
3.3 Formal vs. Actual Parameters
- Formal Parameters (形参): Parameters defined in the method declaration. They follow variable definition format, such as
int value. - Actual Parameters (实参): Arguments passed during method invocation. These can be variables or literal values, such as
50ornumber.
3.4 Practical Exercise: Printing Odd Numbers in a Range
Requirement: Create a method that prints all odd numbers between n and m.
Approach:
- Define a method named
printOddNumbers - Add two int-type formal parameters to receive caller-provided arguments
- Implement a for loop iterating from n to m
- Add conditional logic to identify and print odd numbers
- Invoke the method from main with two actual parameters
public class OddNumberPrinter {
public static void main(String[] args) {
printOddNumbers(5, 25);
}
public static void printOddNumbers(int start, int end) {
System.out.println("Odd numbers between " + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
if (i % 2 != 0) {
System.out.println(i);
}
}
}
}
- Methods with Return Values
4.1 Defining Methods That Return Values
Syntax:
public static returnType methodName(parameter) {
return value;
}
Examples:
public static boolean checkEvenNumber(int number) {
return number % 2 == 0;
}
public static int findMaximum(int a, int b) {
return Math.max(a, b);
}
Critical Note: The data type specified in the return statement must match the declared return type.
4.2 Invoking Methods with Return Values
Syntax:
methodName(parameter);
dataType variable = methodName(parameter);
Examples:
checkEvenNumber(7);
boolean isEven = checkEvenNumber(7);
Recommendation: Return values should typically be stored in variables; otherwise, the returned data is lost and serves no purpose.
4.3 Practical Exercise: Finding Maximum of Two Numbers
Requirement: Design a method that returns the larger of two numbers provided as parameters.
Approach:
- Declare a method with two formal parameters
- Use conditional logic to compare values and return the result
- Call the method from main and store the returned value
public class MaximumFinder {
public static void main(String[] args) {
// Direct output
System.out.println("Maximum: " + getMaximum(10, 25));
// Store result in variable
int result = getMaximum(30, 18);
System.out.println("Stored result: " + result);
// Use result in loop
for (int i = 1; i <= result; i++) {
System.out.println("Iteration: " + i);
}
}
public static int getMaximum(int a, int b) {
return (a > b) ? a : b;
}
}
- Method Best Practices and Considerations
5.1 Universal Method Format
Standard Template:
public static returnType methodName(parameter) {
methodBody;
return data;
}
Component Breakdown:
Method Design Guidelines:
-
Determine Return Type:
voidif no data is returned- Specific data type if a value is returned
-
Identify Parameters:
- Specify paramter types and count based on method requirements
Invocation Guidelines:
voidmethods: Direct invocasion- Non-void methods: Store result in a variable
5.2 Common Pitfalls to Avoid
Nested Method Definitions (Not Allowed):
public class MethodExample {
public static void main(String[] args) { }
public static void firstMethod() {
// This causes a compilation error!
public static void nestedMethod() {
// Code here
}
}
}
Return Statement Rules:
public class ReturnExample {
public static void main(String[] args) { }
public static void processData() {
// Valid: void method can have empty return
return;
// This line is unreachable
// System.out.println("unreachable");
}
}
Important: In void methods, return can be omitted entirely or used alone without a value. Code after a return statement is unreachable.
- Method Overloading
6.1 Understanding Method Overloading
Method overloading occurs when multiple methods in the same class share the same name but differ in their parameter lists.
Requirements for Overloading:
- Methods must be in the same class
- Methods must have the same name
- Parameters must differ (different types or different counts)
Key Principles:
- Overloading relates to method definition only; it does not affect invocation syntax
- Overloading is determined by method name and parameter list only—return type does not factor into overloading resolution
- Two methods cannot be differentiated solely by their return types
6.2 Valid Overloading Examples
public class ValidOverloads {
// Method with int parameter
public static void processValue(int a) { }
// Method with double parameter (different type)
public static void processValue(double a) { }
}
// Another valid example
public class ValidOverloads {
// Method with single int parameter
public static int calculate(int a) { return a; }
// Method with two int parameters (different count)
public static int calculate(int a, int b) { return a + b; }
}
6.3 Invalid Overloading Examples
// Error: Return type alone does not create overloading
public class InvalidExample {
public static void compute(int a) { }
public static int compute(int a) { return 0; } // Compilation error
}
// Error: Different classes = different scope
public class FirstClass {
public static void compute(double a) { }
}
public class SecondClass {
public static int compute(double a) { return 0; } // Not an overload
}
6.4 Overloading Exercise: Number Comparison
Requirement: Implement methods that compare two integers for equality, supporting all integer types (byte, short, int, long).
Approach:
- Define base comparison method with int parameters
- Create overloaded versions for byte, short, and long types
- Test all implementations
public class NumberComparator {
public static void main(String[] args) {
System.out.println("Compare ints: " + areEqual(10, 20));
System.out.println("Compare bytes: " + areEqual((byte) 5, (byte) 5));
System.out.println("Compare shorts: " + areEqual((short) 100, (short) 200));
System.out.println("Compare longs: " + areEqual(50L, 50L));
}
public static boolean areEqual(int a, int b) {
System.out.println("Comparing integers");
return a == b;
}
public static boolean areEqual(byte a, byte b) {
System.out.println("Comparing bytes");
return a == b;
}
public static boolean areEqual(short a, short b) {
System.out.println("Comparing shorts");
return a == b;
}
public static boolean areEqual(long a, long b) {
System.out.println("Comparing longs");
return a == b;
}
}
- Parameter Passing Mechanisms
7.1 Primitive Type Parameters
Key Concept: When a primitive type is passed to a method, the actual value is copied. Changes to the formal parameter do not affect the original variable.
Demonstration:
public class PrimitivePassTest {
public static void main(String[] args) {
int originalValue = 100;
System.out.println("Before modifyValue: " + originalValue);
modifyValue(originalValue);
System.out.println("After modifyValue: " + originalValue);
}
public static void modifyValue(int input) {
input = 200; // This only modifies the local copy
}
}
Output:
Before modifyValue: 100
After modifyValue: 100
Explanation: Each method receives its own独立栈空间 (independent stack space). When the method completes, the stack frame is destroyed, leaving the original variable unchanged.
7.2 Reference Type Parameters
Key Concept: When a reference type (arrays, objects) is passed, the memory address is copied. Both references point to the same object, so modifications through one reference affect the actual object.
Demonstration:
public class ReferencePassTest {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println("Before modifyArray: " + numbers[1]);
modifyArray(numbers);
System.out.println("After modifyArray: " + numbers[1]);
}
public static void modifyArray(int[] data) {
data[1] = 200; // Modifies the actual array object
}
}
Output:
Before modifyArray: 20
After modifyArray: 200
Explanation: Both the original reference and the parameter reference the same heap memory location. After the method executes, the heap object contains the modified values.
7.3 Array Traversal Method
Requirement: Design a method that traverses an array and prints elements in a single line format: [element1, element2, element3]
Key Output Methods:
System.out.println(): Prints content and moves to new lineSystem.out.print(): Prints content without newlineSystem.out.println(): Empty call creates a newline
public class ArrayTraversalDemo {
public static void main(String[] args) {
int[] data = {11, 22, 33, 44, 55};
printArrayElements(data);
System.out.println("Continuing with other logic...");
}
public static void printArrayElements(int[] inputArray) {
System.out.print("[");
for (int i = 0; i < inputArray.length; i++) {
if (i == inputArray.length - 1) {
// Last element - no trailing comma
System.out.println(inputArray[i] + "]");
} else {
// Add comma between elements
System.out.print(inputArray[i] + ", ");
}
}
}
}
Output:
[11, 22, 33, 44, 55]
Continuing with other logic...
7.4 Finding Maximum Value in Array
Requirement: Design a method that returns the maximum value from an integer array.
Approach:
- Initialize with first element as temporary maximum
- Iterate through remaining elements
- Update maximum when larger value is found
- Return the discovered maximum
public class ArrayMaxFinder {
public static void main(String[] args) {
int[] values = {11, 55, 22, 44, 33};
int maximum = findArrayMaximum(values);
System.out.println("Maximum value: " + maximum);
}
public static int findArrayMaximum(int[] inputArray) {
int currentMax = inputArray[0];
for (int i = 1; i < inputArray.length; i++) {
if (currentMax < inputArray[i]) {
currentMax = inputArray[i];
}
}
return currentMax;
}
}
7.5 Simultaneous Maximum and Minimum Retrieval
Requirement: Design a method that returns both maximum and minimum values from an array simultaneously.
Limitation: The return statement can only transmit one value.
Solution: Return an array containing both values.
public class MinMaxFinder {
public static void main(String[] args) {
int[] values = {11, 55, 33, 22, 44};
int[] results = findMinAndMax(values);
System.out.println("Minimum: " + results[0]);
System.out.println("Maximum: " + results[1]);
}
public static int[] findMinAndMax(int[] inputArray) {
int currentMax = inputArray[0];
int currentMin = inputArray[0];
for (int i = 1; i < inputArray.length; i++) {
if (currentMax < inputArray[i]) {
currentMax = inputArray[i];
}
if (currentMin > inputArray[i]) {
currentMin = inputArray[i];
}
}
return new int[] {currentMin, currentMax};
}
}