Thinking Logic of computer program (11)-Initial knowledge function

Source: Internet
Author: User
Tags modifiers

Function

In the previous sections we introduced the basic types of data, basic operations, and process control, which can already be written in a number of applications.

But if you need to do something often, similar code needs to be repeated many times, such as finding a number in an array, looking for a number for the first time, a second may look for another number, a number per check, a similar code needs to be rewritten again, very verbose. In addition, there are a number of complex operations that can be divided into many steps, which are difficult to understand and maintain if all are put together.

Computer programs use the concept of functions to solve the problem of using functions to reduce duplication of code and to decompose complex operations, and in this section we'll talk about functions in Java, including the basics of functions and some details.

Defining functions

The concept of function, we have been exposed to mathematics, the basic format is y = f (x), represents the X-to-y correspondence, given the input x, after the function transformation F, output Y. The concept of a function in a program is similar to that of input, operation, and output, but it represents a subroutine that has a name indicating its purpose (analogy F) with 0 or more parameters (analogy x), which may return a result (analogy y). Let's take a look at two simple examples:

int sum (intint sum = a +return sum;} void for(int i=0;i<3;i++) {System.out.println ();}}       

The first function is called Sum, whose purpose is to sum the two numbers in the input, with two input parameters, int integers A and B, which operate on the sum of two numbers, the sum of which is placed in the variable sum (this sum has nothing to do with the sum of the function name). We then use the return statement to return the result, and the first public static is the modifier of the function, which we'll introduce later.

The second function is called Print3lines, which is designed to output three blank lines on the screen, it has no input parameters, the operation is to use a loop to output three blank lines, it has no return value.

The above code is relatively simple, mainly to demonstrate the basic syntax structure of the function, namely:

Modifier return value type  function name (parameter type parameter name, ...) {    action ...     return value;} 

The main components of a function are:

    • Function Name: The name is indispensable and represents the function's function.
    • Parameters: The parameter has 0 to many, each parameter has the parameter data type and the parameter name composition.
    • Action: The specific operation code of the function.
    • Return value: function can have no return value, no return value type is written void, some words in the function code must use the return statement to return a value, the type of the value needs to be the same as the declared return value type.
    • Modifiers: In Java, functions have many modifiers, each representing different purposes, and in this section we assume that the modifiers are public static, and that the purpose of these modifiers is not discussed at this stage.

This is the syntax for defining a function, which defines a subroutine with a definite function, but the definition function itself does not execute any code, the function is executed and needs to be called.

Function call

In Java, any function needs to be placed in a class, the class we have not introduced, we can temporarily consider the class as a function of a container, that is, the function is placed in a class, the class includes a number of functions, Java functions are generally called methods, we do not specifically distinguish between functions and methods, may be used interchangeably. A class can define multiple functions, within which a function called main can be defined, in the form of:

void Main (string[] args) {      ...}

This function has a special meaning, indicating the entry of the program, string[] args represents the parameters received from the console, we can temporarily ignore it. When running a program in Java, you need to specify a class that defines the main function, and Java looks for the main function and executes it from the main function.

A person who has just begun to learn programming may mistakenly assume that the program is executed from the first line of code, which is wrong, regardless of where the main function is defined, the Java function will find it first and then execute it from its first line.

In addition to defining variables and manipulating data, the main function can call other functions as follows:

void Main (string[] args) {    int a = 2int b = 3int sum = sum (a, b); SYSTEM.OUT.PRINTLN (sum); Print3lines (); SYSTEM.OUT.PRINTLN (sum (3,4));}     

The main function first defines two variables A and B, then calls the function sum, passes A and B to the SUM function, and assigns the result of sum to the variable sum. The calling function needs to pass parameters and process the return value.

For starters, it is important to note that the names of parameters and return values have no special meaning. The parameter names A and b in the caller main, and the arguments in the function definition sum the names A and B just happen to be the same, they can be different, and there is no relationship between names, the SUM function cannot use the name in the main function, and vice versa. The name of the sum variable in the caller main and the sum variable in the SUM function also happens to be the same, completely different. In addition, variables and functions can take the same name, but it also happens, the name does not mean that there is a special meaning.

Call function If there are no arguments to pass, also parentheses (), such as Print3lines ().

The passed parameter is not necessarily a variable, it can be a constant, or it can be an operation expression, which can be the result of a function's return. such as: System.out.println (sum (3,4)); The first function calls sum (3,4), the arguments passed are constants 3 and 4, and the second function called System.out.println passes the parameter that is the return result of sum (3,4).

With regard to parameter passing, it is simple to summarize that declaring parameters when defining a function is actually defining variables, except that the values of these variables are unknown, and arguments are passed when the function is called, in effect assigning values to variables in the function.

Functions can call other functions in the same class, or they can call functions in other classes, and we have used a function that outputs a binary representation of an integer in the previous sections, tobinarystring:

int a =; System.out.println (Integer.tobinarystring (a));

Tobinarystring is a function in the integer class with the modifier public static, which can be called directly by adding the class name and the.

Basic Summary of functions

For code that needs to be executed repeatedly, you can define a function and then call it where you want, which reduces the duplication of code. For complex operations, you can divide the operation into multiple functions, which makes the code easier to read.

As we have described earlier, program execution is basically only sequential execution, conditional execution, and loop execution, but a more complete description should include the function's invocation process. The program starts from the main function, and when it encounters a function call, it jumps into the function, the function calls the other functions, then goes to the other functions, the function returns after the call, returns to the main function and the main function does not have to execute the statement after the program ends. The details of the execution process are described in more depth in the next section.

In Java, the position of the function in the program code is not related to the order in which it is actually executed.

The definition and basic invocation of a function should be easy to understand, but there are many details that may confuse the novice, including parameter passing, return, function naming, calling process, and so on.

Parameter passing

Array parameters

Arrays are not the same as parameters, and primitive types do not have any effect on variables in the caller, but arrays are not, modifying elements in the array within a function modifies the contents of the array in the caller. Let's look at an example:

void Reset (int[] arr) {for    (int i=0;i<arr.length;i++) {Arr[i] = i;}} voidint[] arr = {10,20,30,40 for(int i=0;i<arr.length;i++) {System.out.println (arr[i]);}} 

Assigning values to the parameter array elements within the Reset function will also change the value of the array arr in the main function.

This is actually easy to understand, we introduced in the second section, an array variable has two blocks of space, one for storing the contents of the array itself, another to store the contents of the location, the array variable assignment does not affect the original array content itself, but only the array variable point to a different array of content space.

In the example above, the array variable in the function parameter arr and the array variable in the main function are stored in the same location, and the array content itself has only one copy of the data, so modifying the contents of the array element in reset is exactly the same as in main.

Variable-length parameters

The functions described above, the number of parameters are fixed, but sometimes, may want to be the number of parameters is not fixed, for example, to find a number of the maximum value, may be two or more, Java supports variable length parameters, as shown in the following example:

PublicStaticint Max (int min,int ... a) {int Max = min; for (int i=0;i<a.length;i++ ) {if (Max<a[i]) {max =< Span style= "COLOR: #000000" > A[i]; }} return Max;} public static void main (string[] args) {System.out.println (max (0        

This Max function takes a minimum value and several parameters of variable length to return the maximum value. The syntax for variable-length parameters is to add three points after the data type ..., within a function, a variable-length parameter can be considered an array, the variable-length parameter must be the last parameter in the argument list, and a function can have only one variable-length parameter.

The variable-length parameter is actually converted to an array parameter, that is, the function declares max (int min, int ... a) to actually convert to max (int min, int[] a), and when the main function calls Max (0,2,4,5), it is actually converted to call Max ( 0, New int[]{2,4,5}), using variable length parameters primarily simplifies code writing.

Return

Meaning of Return

For beginners, we emphasize the meaning of return. When a function returns a value of type void and does not return, it is executed automatically at the end of the function. Return is used to end the function execution and return the caller.

Return can be used anywhere within the function, either at the end of the function or in the middle, within the IF statement, within the For loop, to end the function execution prematurely, and return the caller.

function return value type is void also can use return, that is, return, without a value, meaning is to return to the caller, but there is no return value.

Number of return values

There can be at most one return value for a function, so what if you need more than one return value? For example, to calculate the maximum number of first three in an array of integers, you need to return three results. This can use an array as the return value, create an array of three elements within the function, and then assign the first three results to the corresponding array elements.

What if the return value needed is a composite result? For example, find all occurrences of a character array, and the number of occurrences of the repetition. This can be used as the return value of the object, and we introduce classes and objects in subsequent chapters.

I want to say that although the return value can have at most one, but actually one is enough.

function naming

Each function has a name that indicates the meaning of the function, can the name be repeated? In different classes, the answer is yes, in the same class, it depends on the situation.

In the same class, the function can have the same name, but the argument cannot be the same as the parameter number is the same, the parameter type of each position is the same, but the parameter is not counted, the return value type is not counted. In other words, the uniqueness of the function is: Class name _ Function Name _ parameter 1 type _ parameter 2 type _ ... The parameter n type.

A phenomenon that has the same name but different parameters in the same class is generally called a function overload. Why do you need function overloading? It is generally because the function wants to express the same meaning, but the number of parameters or the type is different. For example, for the maximum value of two numbers, four functions are defined in the Java Math Library, as follows:

Call procedure

Matching process

We did not specifically describe the type of the parameter before we introduced the function call. It is explained here that parameter passing is actually assigning a value to the parameter, and that the data passed by the caller needs to match the type of the parameter declared by the function, but not exactly the same. What do you mean? The Java compiler automatically casts the type and looks for the most matching function. Say, for example:

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

argument is of character type, but math does not define the Max function for character type, as we explained before, char is actually an integer, Java converts char to int automatically, and then calls Math.max (int a, int b), and the screen outputs an integer result of 98.

What if the Max function for type int is not defined in math? The call will also succeed, calling the long type Max function, if long does not? The Max function of the float type is called, and if float does not, it will be called double type. The Java compiler will automatically look for the most matching.
In the case of only one function (that is, no overloading), the function is called whenever a type conversion is possible, and in the case of a function overload, the most matching function is called.

Recursive

The function is called by other functions in most cases, but the function can also invoke itself, calling its own function called the recursive function.

Why do you need to call yourself? Let's look at an example of the factorial of a number, the factorial of a number n in mathematics, expressed as n!, whose value is defined as:

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

The factorial of 0 is the value of the factorial of the 1,n is the value of the factorial of the n-1 multiplied by N, the definition is a recursive definition, in order to find the value of n, you need to n-1 value, until 0, and then backward. Recursive expressions are easily implemented with recursive functions, and the code is as follows:

Long factorial (int n) {    if (n==0return 1;} Elsereturn n*factorial (n-1);}}       

It should seem easier to understand, similar to a mathematical definition.

Recursive functions are often relatively simple in form, but recursion actually has overhead, and improper use can result in unexpected results, such as this call:

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

The system will not give any results, but will throw an exception, the exception we introduced in subsequent chapters, here is understood as a system error can be, the exception type is: Java.lang.StackOverflowError, what does this mean? This represents a stack overflow error, and to understand this error, we need to understand the implementation principle of the function call (described in the next section).

What if we can't do it recursively? Recursive functions can often be converted to non-recursive forms, implemented through a number of data structures (described in subsequent chapters) and loops. For example, in the case of factorial, the non-recursive form is defined as:

N!=1x2x3x...xn

This can be implemented in a loop, with the following code:

Long factorial (int n) {    long result = 1 for(int i=1; i<=n; i++) {result*=return  result;}       

Summary

function is an important structure of computer program, through functions to reduce duplication of code, decomposition of complex operations is a computer program an important way of thinking. In this section we describe the basic concepts of functions, as well as some details about parameter passing, return values, overloading, recursion.

However, in Java, functions also have a large number of modifiers, such as public, private, static, final, synchronized, abstract, etc., this article assumes that the modifier of the function is public static, in subsequent articles, Let's introduce these modifiers again. You can also declare exceptions in a function, and we'll leave it to the next article.

When we introduce the recursive function, we see a system error, Java.lang.StackOverflowError, understand the error, we need to understand the implementation mechanism of the function call, let us introduce the next section.

----------------

Thinking Logic of computer program (11)-Initial knowledge function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.