Method Basics

Methods are the basic building blocks for organizing code. This lesson covers how to define and use methods in Java.

What is a Method

A method is a block of code that performs a specific task and can be called repeatedly.

Benefits of Methods

Benefit Description
Code reuse Write once, call many times
Clear logic Break complex problems into smaller methods
Easy to maintain Changes only need to be made in one place

Method Definition

Syntax

JAVA
modifier returnType methodName(parameterList) {
    // Method body
    return returnValue;
}

Example: Simple Method

JAVA
public class MethodDemo {
    // Define method
    public static void sayHello() {
        System.out.println("Hello, Java!");
    }
    
    public static void main(String[] args) {
        // Call method
        sayHello();
        sayHello();  // Can be called multiple times
    }
}
▶ Try it Yourself

Output:

TEXT
Hello, Java!
Hello, Java!

Method Parameters

Parameters allow methods to receive external data.

No Parameters

JAVA
public static void printLine() {
    System.out.println("================");
}

With Parameters

JAVA
public static void greet(String name) {
    System.out.println("Hello, " + name + "!");
}

Multiple Parameters

JAVA
public static int add(int a, int b) {
    return a + b;
}

Example: Method Parameters

JAVA
public class ParamDemo {
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
    
    public static int add(int a, int b) {
        return a + b;
    }
    
    public static void printInfo(String name, int age) {
        System.out.println("Name: " + name + ", Age: " + age);
    }
    
    public static void main(String[] args) {
        greet("Alice");           // Hello, Alice!
        greet("Bob");             // Hello, Bob!
        
        int sum = add(3, 5);
        System.out.println("3 + 5 = " + sum);  // 8
        
        printInfo("John", 25);   // Name: John, Age: 25
    }
}
▶ Try it Yourself

Return Values

Methods can return a result to the caller.

With Return Value

JAVA
public static int max(int a, int b) {
    return (a > b) ? a : b;
}

No Return Value (void)

JAVA
public static void printMax(int a, int b) {
    int max = (a > b) ? a : b;
    System.out.println("Maximum: " + max);
}

Example: Return Values

JAVA
public class ReturnDemo {
    public static int max(int a, int b) {
        return (a > b) ? a : b;
    }
    
    public static double average(int a, int b) {
        return (a + b) / 2.0;
    }
    
    public static boolean isEven(int num) {
        return num % 2 == 0;
    }
    
    public static void main(String[] args) {
        System.out.println("max(3, 5) = " + max(3, 5));       // 5
        System.out.println("avg(3, 5) = " + average(3, 5));   // 4.0
        System.out.println("isEven(4) = " + isEven(4));       // true
        System.out.println("isEven(7) = " + isEven(7));       // false
    }
}
▶ Try it Yourself
⚠️ Note: void methods cannot use return value, but can use return; to exit the method early.

Method Overloading

Method overloading means having multiple methods with the same name but different parameter lists in the same class.

Overloading Rules

Rule Description
Same method name Required
Different number of parameters Allowed
Different parameter types Allowed
Different parameter order Allowed
Different return type Not considered overloading

Example: Method Overloading

JAVA
public class OverloadDemo {
    public static int add(int a, int b) {
        return a + b;
    }
    
    public static int add(int a, int b, int c) {
        return a + b + c;
    }
    
    public static double add(double a, double b) {
        return a + b;
    }
    
    public static String add(String a, String b) {
        return a + b;
    }
    
    public static void main(String[] args) {
        System.out.println(add(1, 2));              // 3
        System.out.println(add(1, 2, 3));           // 6
        System.out.println(add(1.5, 2.5));          // 4.0
        System.out.println(add("Hello", "World"));  // HelloWorld
    }
}
▶ Try it Yourself

Varargs (Variable Arguments)

Varargs allow methods to accept a variable number of arguments.

Syntax

JAVA
public static int sum(int... numbers) {
    int total = 0;
    for (int num : numbers) {
        total += num;
    }
    return total;
}

Example: Varargs

JAVA
public class VarargsDemo {
    public static int sum(int... numbers) {
        int total = 0;
        for (int num : numbers) {
            total += num;
        }
        return total;
    }
    
    public static void printNames(String... names) {
        for (String name : names) {
            System.out.println(name);
        }
    }
    
    public static void main(String[] args) {
        System.out.println(sum(1, 2));           // 3
        System.out.println(sum(1, 2, 3));        // 6
        System.out.println(sum(1, 2, 3, 4, 5));  // 15
        
        printNames("Alice", "Bob", "Charlie");
    }
}
▶ Try it Yourself
⚠️ Note: Varargs must be the last parameter in a method, and a method can only have one varargs parameter.

Parameter Passing

Java uses "pass by value" for parameter passing.

Primitive Type Passing

JAVA
public static void changeValue(int num) {
    num = 100;  // Only modifies local variable
}

public static void main(String[] args) {
    int x = 10;
    changeValue(x);
    System.out.println(x);  // 10, unchanged
}

Reference Type Passing

JAVA
public static void changeArray(int[] arr) {
    arr[0] = 100;  // Modifies array content
}

public static void main(String[] args) {
    int[] arr = {1, 2, 3};
    changeArray(arr);
    System.out.println(arr[0]);  // 100, modified
}
💡 Understanding: Primitive types pass a copy of the value. Reference types pass a copy of the address.

Method Call Stack

When methods are called, stack frames are created in stack memory.

JAVA
public static void main(String[] args) {
    methodA();
}

public static void methodA() {
    methodB();
}

public static void methodB() {
    System.out.println("Hello");
}

Call order: main → methodA → methodB → completes → returns to methodA → returns to main

❓ Frequently Asked Questions

Q What's the difference between a method and a function?
A In Java, methods must belong to a class. Functions in other languages are static methods of classes in Java.
Q When should I use static methods?
A When the method doesn't need to access object state. Utility class methods are typically static.
Q Can return be omitted?
A void methods can omit return (they end automatically). Methods with return values must have a return statement.

📖 Summary

📝 Exercises

  1. Method practice: Write methods to calculate the maximum, minimum, and average of two numbers
  2. Overloading practice: Write multiple print methods that support different parameter types
  3. Varargs: Write a method that calculates the average of any number of values

Next Lesson

In the next lesson, we'll learn about Advanced Methods — recursion, static methods, and method references.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏