Java programming logic (11) - a function of acquaintance

function

The previous section we introduced the basic types of data, basic operations and process control, the use of these procedures have to write a lot.

But if you need to always do a certain operation is similar to the code needs to be repeated many times to write, for example, to find a number in an array, the first time to find a number, the second number might find another, each a check number, similar code needs to be rewritten again, very wordy. In addition, there are a number of complex operations, may be divided into a number of steps, if put together, the code difficult to understand and maintain.

The computer program uses the concept of function to solve this problem, namely the use of functions to reduce duplication of code and break down complex operation, in this section we talk about functions in Java, including basic functions and some of the details.

Defined Functions

Function concept, we learn math are contacted, the basic format is y = f (x), x to y represents the correspondence between a given input x, after conversion function F, an output y. Its function is similar to the concept of the program, there are input, operation, and an output composition, but it represents subprogram, the subprogram has a name, which represents the object (analog F), zero or more parameters (analog x), it is possible to return a result (analog y). Let's look at two simple examples:

Copy the code
public static int sum(int a, int b){
    int sum = a + b;
    return sum;
}

public static void print3Lines(){
    for(int i=0;i<3;i++){
        System.out.println();
    }
}
Copy the code

The first function name is a sum, it is the object of the summing input of two numbers, two input parameters, int are the integers a and B, its operation is a sum of two numbers, the summation result of the discharge in the variable sum (the sum of the sum and the function name has nothing to do), and then use the return statement returns the results, is the beginning of the public static modifier function, we introduce the follow-up.

The second function name is print3Lines, its purpose is to output three blank lines on the screen, it has no input parameters, output operation is to use a three blank line loop, it has no return value.

The above code are relatively simple, the main function of the basic grammatical structure of presentation, namely:

Modifier type of the function return value name (parameter type parameter name, ...) {
    operating...
    return Return value;
}

The main part of the function are:

  • Function name: The name is essential, a functional function.
  • Parameters: 0 There are multiple parameter, each parameter has a parameter name of the parameter data type and composition.
  • Operation: operation of the specific function code.
  • Return value: The function can not return a value, if not written return type void, any, must use the return statement in the function code returns a value, the value of this type of statement needs and return the same value type.
  • Modifiers: Java has a lot of function modifier, respectively, for different purposes, in this section we assume modifier is public static, and not discuss the purpose of these modifiers.

These are the syntax defined functions defined function is defined subroutines period has a clear function, but the definition of the function itself does not execute any code, the function to be executed, need to be called.

Function call

In Java, any function needs to be placed in a class, the class that we have not covered, we have the class could be seen as a function of container that functions in a class, the class includes a plurality of functions, Java is generally a function is called method, we are not particularly distinguished functions and methods may be used interchangeably. A class which can define a plurality of functions, which can define a class called main function of forms such as:

public static void main(String[] args) {
      ...
}

This function has a special meaning, represents the entrance procedures, String [] args represents receiving from the console to the parameters, we can ignore it. Java run a program when you need to specify a definition of the main functions of the class, Java will look for the main function, and started from the main function.

People just started to learn programming may mistakenly think the program started from the first line of code, it is wrong, no matter where the main function is defined, Java function will first try to find it, and then it started from the first row.

In addition to the main function can define a variable, operational data may also call other functions, as follows:

Copy the code
public static void main(String[] args) {
    int a = 2;
    int b = 3;
    int sum = sum(a, b);

    System.out.println(sum);
    print3Lines();
    System.out.println(sum(3,4));
}
Copy the code

First, the main function defines two variables a and b, then calls the function sum, and a and b are passed to a sum function, the result of sum and then assigned to the variable sum. Calling routine to pass parameters and return values ​​processed.

For starters it should be noted here that the parameters and return values ​​is not the name of special meaning. The name of the caller main parameters of a and b, and function definitions sum of the parameters a and b name just happened, like it, they can not be the same, and there is no relationship between the name, sum function can not be used in the main function name and vice versa. The name of the caller in the main function of the sum variable and the sum of the sum of the variables is the same as it happened, completely different. In addition, variables and functions can take the same name, but also happen to it, it does not mean the same name has a special meaning.

If you do not call the function parameters to be passed, but also parentheses (), as print3Lines ().

Parameter passed is not necessarily a variable can be a constant, it can be an arithmetic expression, it can return the result of a function. Such as: System.out.println (sum (3,4)); the first function call sum (3,4), the transmission parameters are constant 3 and 4, the second function call parameters passed System.out.println It is the sum (3,4) returns the result.

On parameter passing, briefly summarize, the statement parameters defined functions, in fact, is the definition of a variable, but the value of these variables is unknown, passing parameters when calling the function, in fact, to the function of the variable assignment.

The same function can call other functions in a class, or you can call functions in other classes, we used the function outputs a binary representation of integers in the previous sections, toBinaryString:

int a = 23;
System.out.println(Integer.toBinaryString(a));

toBinaryString Integer class is a modifier to public static function, prefixed by the class name and direct calls.

The basic function Summary

For repeated execution code needs to be defined function, then the call where needed, thus reducing code duplication. For complex operations, the operation can be divided into a plurality of functions, so that the code will be more readable.

We introduced earlier, program execution is basically only order execution, conditional execution and cycle execution, but a more complete description of the process should include calling function. Program main function begins execution, a function call when met, will jump into the inner function, the function calls other functions, will then enter other function, the function returns will continue to back the call statement, to return to the main function and main after the program statement to execute the function does not end. The next section we will be more in-depth information on the implementation details of the process.

In Java, the location and order of the actual execution of the function in the program code is not related.

Definitions and basic call functions should be relatively easy to understand, but there are a lot of details may result in confusion for beginners, including parameter passing, return, function name, call process, and we discuss each case.

Parameter passing

Array parameter

Array as a parameter to the base type is not the same, basic types will not have any impact on the caller's variables, arrays but not modify elements in the array will modify the contents of the array of the caller within the function. We look at an example:

Copy the code
public static void reset(int[] arr){
    for(int i=0;i<arr.length;i++){
        arr[i] = i;
    }
}

public static void main(String[] args) {
    int[] arr = {10,20,30,40};
    reset(arr);
    for(int i=0;i<arr.length;i++){
        System.out.println(arr[i]);
    }
}
Copy the code

Array element assigned to the parameter in a reset function, also becomes a function of the value of the array arr main.

This is actually easy to understand, we have introduced in the second quarter, an array variable has two spaces for storing an array of content itself, the other location for storing content, to an array variable assignment does not affect the original array the content itself, but will only make the array variable to point to a different array of content space.

In the above example, the array variable function parameter array variable arr arr and the main function is the same memory location, the contents of the array itself is only a piece of data, so the contents of the array element in modifying and reset in main modification is exactly the same.

Variable length parameter

Function, the number of parameters described above are fixed, but sometimes, it may be desirable not fixed number of parameters, such as the maximum number of seeking the number may be two, possibly more, Java support variable length parameters, in the following example:

Copy the code
public static int max(int min, int ... a){
    int max = min;
    for(int i=0;i<a.length;i++){
        if(max<a[i]){
            max = a[i];
        }
    }
    return max;
}

public static void main(String[] args) {
    System.out.println(max(0));
    System.out.println(max(0,2));
    System.out.println(max(0,2,4));
    System.out.println(max(0,2,4,5));
}
Copy the code

The max function takes a minimum value, and a plurality of variable length parameters, which returns the maximum value. Syntax variable length parameter data type is added after the three points ..., in function, is variable-length argument can be regarded as an array, a variable length parameter must be the last one of the parameters in the list, is also a function only one variable length parameter.

Variable length parameter is actually converted to array parameters, i.e., the function declaration max (int min, int ... a) will actually be converted to max (int min, int [] a), the function call in the main max (0,2,4,5) when the call is actually converted to max (0, new int [] {2,4,5}), parameters are mainly using variable length codes written in simplified.

return

return of meaning

For starters, we emphasize the meaning of lower return. Type of function return value and a case where there is no return of the void, the function will be executed automatically returns to the end. return for the end of the function execution returns to the caller.

return can be used anywhere within the function, may in the end of the function, can be in the middle, can be in the if statement in the for loop can be used for early termination of the function execution returns to the caller.

Function returns a value of type void can also use return, namely return ;, do not bring value, meaning a return to the caller, but no return value only.

Returns the number of values

The return value of a function can only have a maximum of one, that if the situation requires multiple return values ​​it? For example, calculate the maximum number of three in an array of integers, three need to return a result. This array can be used as the return value, to create an array of three elements in the function, then the result is assigned to the first three elements of the corresponding array.

If the actual needs of the return value is a composite result? For example, to find an array of characters, all the characters and the number of recurring recurring. The return value can be used as an object, we introduce classes and objects in subsequent sections.

I want to say that, although the return value can only have a maximum of one, but a fact is enough.

Function name

Each function has a name, the name represents this sense function names can repeat it? In a different class, the answer is yes, in the same class, depending on the situation.

Same class, may function the same name, but the parameter is not the same, the same refer to the same number of parameters, each parameter type the same position, but not the name of the parameter, return type is not too. In other words, the only function of the label that is: the name of the class function name _ _ _ Parameter Parameter Type 1 Type 2 Type _... parameter n.

The same function name in the same class but with different parameters of the phenomenon, commonly referred to as function overloading. Why do we need function overloading it? General sense because the function would like to express is the same, but not the same type or number of parameters. For example, selecting the maximum value of the two numbers, in the Java library Math four functions is defined as follows:

The calling process

Matching process

When introduced before the function call, we have not specified the type of the parameter. Explain here, the parameter is actually passed to the parameter assignment, the data transfer needs of the caller and the parameter type function declarations are matched, but does not require exactly the same. What does that mean? Java compiler will automatically convert the type, function and find the best match. For example:

char a = 'a';
char b = 'b';
System.out.println(Math.max(a,b));

Parameter is a character type, but does not define for Math and character type max function, we described earlier, is actually a char integer, Java will automatically convert char to int, then call Math.max (int a, int b), integer result output screen 98.

If Math function is not defined max for int type it? Calls will be successful, it will call the max function type long, long if it did not? It calls the float type max function, if there is no float, double type of calls. Java compiler will automatically find the best match.
In the case of only one function (ie not overloaded), as long as you can type conversion, it will call the function, in the presence of function overloading, the function will be called the best match.

Recursion

In most cases the called function are other functions, but in fact the function can call its own, call your own function called recursive functions.

Why do I need to call their own ourselves? We look at an example, a factorial of the number, a number mathematics factorial of n, expressed as the value of n !, which is defined like this:

0!=1
n!=(n-1)!×n

0 factorial is 1, the value of n is the factorial of n-1 factorial value is multiplied by n, a recursive definition is defined, for the sake of the value of n, n-1 must first request value until 0, then turn back retreat. Recursive calculation expression easily achieved with a recursive function, as follows:

Copy the code
public static long factorial(int n){
    if(n==0){
        return 1;
    }else{
        return n*factorial(n-1);
    }
}
Copy the code

Look should be relatively easy to understand, and similar mathematical definition.

Recursive function is often relatively simple in form, but in fact there is a recursive overhead, and improper use, unexpected results can occur, for example, this call:

System.out.println(factorial(10000));

The system does not give any result, and will throw an exception, we have an exception in subsequent sections, but here understood as a system error on it, abnormal type: java.lang.StackOverflowError, What does it mean? This means that a stack overflow error, to understand this wrong, we need to understand the implementation principle function call (lower section).

If that does not work recursively how to do it? Can convert a non-recursive function often recursive form, be realized by some data structure (described later chapters), and cyclic. For example, the factorial example, non-recursive form is defined as:

n!=1×2×3×…×n

This cycle can be achieved, as follows:

Copy the code
public static long factorial(int n){
    long result = 1;
    for(int i=1; i<=n; i++){
        result*=i;
    }
    return result;
}
Copy the code

summary

Is an important function of the structure of a computer program, by a function to reduce the duplication of code, the decomposition operation is a complicated computer program important way of thinking. In this section we introduce the basic concepts of function, as well as on parameter passing, return value, overloading, some details recursive aspects.

But in Java, there are a lot of modifiers function, such as public, private, static, final, synchronized, abstract and so on, this article assumes the function modifier is public static, in subsequent articles, we will introduce these modifiers. Function can also declare exceptions, we are left to subsequent article describes.

Introducing recursive function, we see a system error, java.lang.StackOverflowError, understand this wrong, we need to understand the implementation mechanism of function calls, so our next section.

Guess you like

Origin www.cnblogs.com/ivy-xu/p/12383280.html