Interview 13: does the method call optional parameters or fixed parameters first?

Posted by Concat on Thu, 06 Jan 2022 02:27:13 +0100

Interview collection: https://gitee.com/mydb/interview

Optional parameters (varargs) are new features in JDK 5, also known as variable length parameters or variable parameters. It means that "..." can be used in the parameters of a method To indicate that this method can accept infinite parameters. This representation method is called optional parameters.
The syntax of optional parameters is as follows:

public void method(data type... Parameter name){
    // Method body
}

The basic usage of optional parameters is as follows:

public class ArgumentExample {
    public static void main(String[] args) {
        // Call optional parameters
        method("Java");
        System.out.println();
        // Call optional parameters
        method("MySQL", "Redis");
        // Call optional parameters
        System.out.println();
        method("Spring", "Spring MVC", "Spring Boot");
    }
    /**
     * Optional parameter method
     */
    public static void method(String... names) {
        for (String item : names) {
            System.out.println(item);
        }
    }
}

The execution results of the above procedures are shown in the figure below:

Fixed parameters

The concept of fixed parameters is just opposite to that of optional parameters. Fixed parameters are ordinary parameters. A method has a fixed type and number of parameters without "..." A modifier is a fixed parameter. All method parameters before JDK 5 are fixed parameters, as shown in the following code:

public class ArgumentExample {
    public static void main(String[] args) {
        method("Java");
    }
    /**
     * Fixed parameter method
     */
    public static void method(String name) {
        System.out.println("Fixed parameters:" + name);
    }
}

Optional parameter considerations

The following four problems should be paid attention to when using optional parameters.

1. The optional parameters are from 0 to infinity

The number of calls for optional parameters is from 0 to infinity, not from 1 to infinity, which should be noted, as shown in the following code:

public class ArgumentExample {
    public static void main(String[] args) {
        method();
    }
    /**
     * Optional parameter method
     */
    public static void method(String... names) {
        System.out.println("Number of optional parameters:" + names.length);
    }
}

The execution results of the above procedures are shown in the figure below:

As can be seen from the above code, optional parameters can be called normally even if they do not pass any parameters, that is, 0 parameters.

2. A method can only have one optional parameter

There can only be one optional parameter in a method. If there are multiple optional parameters, the program will report an error, as shown in the following figure:

3. Optional parameters must be placed at the end of the method

If the optional parameter is not placed at the end of the method parameter, the compiler will also report an error, as shown in the following figure:

4. Optional parameters and other methods with the same name constitute method overloading

Optional parameters and other methods with the same name can coexist, and they form a method overload, as shown in the following code:

Do you call fixed parameters or optional parameters first?

After introducing the basic knowledge points, let's return to the topic of this article. When there are two types of parameters in a method: fixed parameters and optional parameters, what is the first to call the fixed parameters? Or call the optional parameters first?
Next, let's use a piece of code to test:

public class ArgumentExample {
    public static void main(String[] args) {
        method("Brother Lei talking about programming");
    }
    /**
     * Fixed parameter method
     */
    public static void method(String name) {
        System.out.println("Call fixed parameters:" + name);
    }
    /**
     * Optional parameter method
     */
    public static void method(String... names) {
        System.out.println("Call optional parameters:" + names.length);
    }
}

The results of the above procedures are as follows:

conclusion

It can be seen from the above results that when there are fixed parameters and optional parameters in the program, the fixed parameters are called first rather than the optional parameters.

Cause analysis

Seeing this, some friends may have realized that if you read my last article Why do different return types not count as method overloading It's all clear. Whether to call optional parameters or fixed parameters first? In the previous article, we introduced the priority rules of method overload call: the call priority of optional parameters is the lowest, and there are other call options between fixed parameters and optional parameters. Because some friends didn't notice or didn't see it, I'll briefly review it here.

Priority 1: accurate parameter matching

Method overload calls priority as like as two peas.

Priority 2: automatically convert the calling base type to a larger base type

If it is a basic data type, the second matching principle of method overload call is to automatically convert to a larger basic data type, such as the following code:

public class OverloadExample {
    public static void main(String[] args) {
        OverloadExample example = new OverloadExample();
        example.method(12);
    }

    public void method(long num) {
        System.out.println("call long method");
    }

    public void method(Integer num) {
        System.out.println("call Integer method");
    }

    public void method(Object num) { 
        System.out.println("call Object method");
    }

    public void method(int... num) { // Optional parameters
        System.out.println("call int... method");
    }
}

The execution results of the above procedures are shown in the figure below:

Priority 3: automatic packing / unpacking matching

If there is a packing type corresponding to the basic type or a method overload of the basic type corresponding to the packing type, the method overload of automatic boxing or automatic unpacking will be called first, as shown in the following code:

public class OverloadExample {
    public static void main(String[] args) {
        OverloadExample example = new OverloadExample();
        example.method(12);
    }

    public void method(Integer num) {
        System.out.println("call Integer method");
    }

    public void method(Object num) {
        System.out.println("call Object method");
    }

    public void method(int... num) { // Optional parameters
        System.out.println("call int... method");
    }
}

The execution results of the above procedures are shown in the figure below:

Priority 4: match the parent class upward according to the inheritance route

When there are parent class parameters, the parent class overloaded method will be called first, as shown in the following code:

public class OverloadExample {
    public static void main(String[] args) {
        OverloadExample example = new OverloadExample();
        example.method(12);
    }

    public void method(Object num) {
        System.out.println("call Object method");
    }

    public void method(int... num) { // Optional parameters
        System.out.println("call int... method");
    }
}

The execution results of the above procedures are shown in the figure below:

Priority 5: optional parameter matching

The call priority of optional parameters is the lowest. When there are only optional parameter methods in a class, the optional parameter methods will be called.

summary

Optional parameters are added in JDK 5 with "..." The format has parameter types. Optional parameters can match 0 to infinite parameters, but there can only be one optional parameter in a method, and the optional parameters should be placed at the end of the method parameters. It can form a method overload with fixed parameters, but the call priority of optional parameters is the lowest.

Right and wrong are judged by ourselves, bad reputation is heard by others, and the number of gains and losses is safe.

The official account: Java interview

Topics: Java Back-end