Java 方法

方法的定义与调用、void、值传递、重载、可变参数与递归。

Beginner
Key PointsJava 只有值传递:基本类型传副本,引用类型传地址副本;重载看参数列表,与返回值无关。

方法的定义

A method is modifiers, return type, name, parameter list and body. void means nothing is returned; with a real return type every path must return.

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

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

    public static void main(String[] args) {
        System.out.println(max(3, 7));
        greet("Tom");
    }
}
Output
7
Hello, Tom

方法调用

Call static methods as Class.method() and instance methods as object.method(). Inside the same class the class name may be omitted, though writing it aids readability.

Java
public class Call {
    static int square(int x) {
        return x * x;
    }

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

    public static void main(String[] args) {
        System.out.println(square(4));
        System.out.println(Call.square(5));

        Call c = new Call();
        System.out.println(c.add(2, 3));
    }
}
Output
16
25
5

void 关键字

void declares no return value; a bare return; exits early, but return value is illegal. Void methods exist for side effects such as printing or writing files.

Java
public class VoidDemo {
    static void printGrade(double score) {
        if (score >= 90) {
            System.out.println("A");
            return;
        }
        System.out.println("B");
    }

    public static void main(String[] args) {
        printGrade(95);
        printGrade(80);
    }
}
Output
A
B

通过值传递参数

Java is pass-by-value only. Primitives pass a copy of the value, so changes stay local; references pass a copy of the address, so mutating the object is visible outside while reassigning is not.

Java
public class PassByValue {
    static void change(int x) {
        x = 99;
    }

    static void mutate(int[] arr) {
        arr[0] = 99;
    }

    static void rebind(int[] arr) {
        arr = new int[]{7};
    }

    public static void main(String[] args) {
        int a = 1;
        change(a);
        System.out.println(a);

        int[] b = {1, 2};
        mutate(b);
        System.out.println(b[0]);

        rebind(b);
        System.out.println(b[0]);
    }
}
Output
1
99
99

方法重载

Same name with a different parameter list (count, types or order) is overloading. The compiler picks by argument types; the return type does not participate.

Java
public class Overload {
    static int add(int a, int b) {
        return a + b;
    }

    static double add(double a, double b) {
        return a + b;
    }

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

    public static void main(String[] args) {
        System.out.println(add(1, 2));
        System.out.println(add(1.5, 2.5));
        System.out.println(add(1, 2, 3));
    }
}
Output
3
4.0
6

可变参数

Type... name accepts any number of arguments of that type and is seen as an array inside. It must be the last parameter and there can be only one.

Java
public class Varargs {
    static int sum(int... nums) {
        int total = 0;
        for (int n : nums) {
            total += n;
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(sum());
        System.out.println(sum(1));
        System.out.println(sum(1, 2, 3));
        System.out.println(sum(new int[]{4, 5}));
    }
}
Output
0
1
6
9

递归

Recursion is a method calling itself; it needs a base case that terminates, otherwise you get StackOverflowError. Decide what the smallest case returns and how each call shrinks the problem.

Java
public class Recursion {
    static int factorial(int n) {
        if (n <= 1) return 1;
        return n * factorial(n - 1);
    }

    static int fib(int n) {
        if (n < 2) return n;
        return fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) {
        System.out.println(factorial(5));
        System.out.println(fib(10));
    }
}
Output
120
55

Friends & Partners