Hello everyone, last time we talked about Java program structure example, this time we will talk about Java function example. Stop gossiping and return to the truth. Let’s Talk Android!
For those familiar with C, functions are nothing new, but I will briefly introduce them. A function is a set of functions. From the point of view of code structure, it is a code block composed of multiple program statements. Function can solve the problem of code reuse. Let’s take an example. If you want to use the sorting function, you just need to implement a sorting function. When you need the sorting function, you can call the sorting function directly instead of implementing a sorting function again.
1. Function prototype
The prototype of a function refers to the function’s name, parameters, and return value. These are the three essential elements of a function. To master function usage, you need to master function prototypes. Next we use pseudocode to illustrate:
void sort(int array[],int size)
{
//do something for sortting
};
Copy the code
In this prototype, the function returns a void variable, the function name is sort, and the function takes two arguments, the first is an array of type int and the second is a variable of type int. The contents of the braces are the program statements in the function that implement sorting.
2. Function overload
Functions can be overloaded in Java, which C does not have. So what is an overload? That is, the same function can operate on different types of data. From the perspective of function prototypes, functions with the same name and different types and numbers of arguments are overloaded. Let’s use pseudocode to demonstrate function overloading:
void sort(int array[],int size)
{
//do something for sortting
};
void sort(float array[],int size)
{
// do something for sortting
};
Copy the code
As you can see, both of these are called sort and take two arguments. The first function takes an array of type int and the second one takes an array of type float. The number of arguments is the same, but the types of arguments are different. Therefore, we call these two functions overloaded.
Function overloading is one of the most important things in Java, and it established the hammar functionality for object orientation, as we will see when we introduce object orientation.
Everyone see officer, on the Java function example let’s introduce here, want to know what examples there are behind, and listen to the next decomposition!