Use of methods in Java

Keywords: Java JavaSE

1. Method concept and use

1.1 what is a method

Method is a code fragment, similar to the "function" in C language.
Function of the method:
1. It is a modular organization code (when the code scale is complex).
2. Make sure that the code is reused, and one code can be used in multiple locations.
3. Make the code better understood and simpler.
4. Directly call the existing method development.

1.2 method definition

Basic syntax:

//Method definition
 Modifier return value type method name([Parameter type parameter...]){
   Method body code;
   [return Return value];
}
//Method call
 Method name(Argument...)
Return value variable=Method name(Argument...)

be careful:
1. At this stage, the modification of the method temporarily adopts ---- > public static (fixed collocation). A modifier defines the method (who can use it).
2. Return value type - > whether to bring out the result after the method is executed.

  • Some methods have return values. When defining methods, you must give the return value type.
  • Some methods have no return value. When defining a method, the position of the return value type is replaced by void.

3. The method must be defined in the class, and the position of the method definition can be above or below the calling position.
4. Method naming: name according to the rules of small hump (the first word is lowercase followed by the first letter is uppercase).
5. Parameter list:

  • Some methods may not have parameters - the () after the method name cannot be omitted
  • Some methods may have one or two parameters

6. Method definitions cannot be nested.
7. There is no concept of "function declaration" in Java. Methods are defined directly in a class.
Code example 1:

//Implement a function to detect whether a year is a leap year
    public static boolean isLeapYear(int year) {
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
            return true;
        } else {
            return false;
        }
    }
        public static void main (String[]args){
            int year = 1900;
            boolean isLeap=isLeapYear(year);//Method call
            System.out.println(isLeap);
        }

Code example 2:

//Realize the addition of two integers
    public static int add(int a,int b){
        return a+b;
    }

    public static void main(String[] args) {
        int x=10;
        int y=20;
        int z=add(x,y);
        System.out.println(z);
    }

1.3 execution process of method call

Method call procedure:
Call method ----- > pass parameters ----- > find method address ----- > execute method body of the called method ----- > return at the end of the called method ----- -- > return to the calling method and continue to execute
be careful:

  • When a method is defined, the code of the method is not executed. Only when called.
  • A method can be called multiple times.
    Code example:
//Calculate 1+ 2!+ 3!+ 4!+ 5!
    //First write a method to calculate the factorial of n
    public static int fac(int n) {
        int rst = 1;
        for (int i = 1; i <= n; i++) {
            rst *= i;
        }
        return rst;
    }
    public static void main12(String[] args) {
        int sum=0;
        for(int j=1;j<=5;j++){
            sum+=fac(j);
        }
        System.out.println(sum);
    }
    //Output result 153

1.4 relationship between arguments and formal parameters*

   the formal parameters of the method are equivalent to the independent variables in the mathematical function, such as sum(n) of 1 + 2 + 3 +... + n= ( 1 + n ) āˆ— n 2 \frac{(1+n)*n}{2} 2(1+n)āˆ—nā€‹.
  in the Java language, the formal parameter of the method is equivalent to the argument n in the sum function, which is used to receive the value passed during the call of the sum function. The name of a formal parameter can be used arbitrarily without any impact on the method. A formal parameter is just a variable that the method needs to use when defining, which is used to save the value passed by the method when calling.
  example 1:

public static int getSum(int N){ //N is a formal parameter
    return (1+N)*N/2;
}
getSum(10);//10 is an argument. When a method is called, the formal parameter N is used to save 10
getSum(100);//100 is an argument. When a method is called, the formal parameter N is used to save 100

  example 2:

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

add(2,3);//2 and 3 are arguments, which are passed to formal parameters a and b when called

Note: in Java, the value of the argument is always copied to the formal parameter. The formal parameter and the argument are essentially two entities.
Code example:

 //Swap two integer variables
    public static void swap(int x,int y ){
        int tmp=x;
        x=y;
        y=tmp;
        System.out.println("swap: x="+x+" y="+y);
    }

    public static void main(String[] args) {
        int a=10;
        int b=20;
        swap(a,b);
        System.out.println("main: a="+a+" b="+b);
    }
//Output results
swap: x=20 y=10
main: a=10 b=20

It can be seen that after the swap function is exchanged, the values of formal parameters x and y are changed, but a and b in the main method are still the values before the exchange, that is, the exchange is not successful.
reason:
   arguments a and b are two variables in the main method, and their spaces are in the stack of the main method, while formal parameters x and y are two variables in the swap method, and the spaces of x and y are in the stack of the swap method runtime. Therefore, arguments a and b and formal parameters x and y are variables without any association. When the swap method is called, only a copy of the values in the arguments a and b is passed to x and Y. therefore, the operation on the formal parameters x and y will not have any impact on the arguments a and b.

1.5 methods without return value

Sometimes the return value of a method can be null. If there is no return value type, it must be written as void
Code example:

class Test{
public static void main(String[] args){
int a=10;
int b=20;
print(a,b);
}
public static void print(int x,int y){
System.out.println("x= "+x+" y= "+y)
}
}

2. Method overload

2.1 why method overloading is required

Let's start with a code:

public class Method {
    //Method overloading
    public static int add(int m, int n) {
        return m + n;
    }
    public static void main(String[] args) {
        int a1=10;
        int b1=20;
        int ret1=add(a1,b1);
        System.out.println(ret1);

        double a2=10.5;
        double b2=20.5;
        double ret2=add(a2,b2);
        System.out.println(ret2);
    }
}
//Compilation error
java: Incompatible types: from double Convert to int There may be losses

The existing add method cannot be used directly because the parameter types do not match.
A simple and crude solution:

public static int addInt(int m, int n) {
        return m + n;
    }
    public static double addDouble(double m, double n) {
        return m + n;
    }
    public static void main(String[] args) {
        int a1=10;
        int b1=20;
        int ret1=addInt(a1,b1);
        System.out.println(ret1);

        double a2=10.5;
        double b2=20.5;
        double ret2=addDouble(a2,b2);
        System.out.println(ret2);
    }
//Output results:
30
31.0

The above code can solve the problem, but it needs to provide many different method names to make the work more cumbersome. Can we give all names as add?

2.2 method overload concept

In Java, if multiple methods have the same name and different parameter lists, they are said to be overloaded.
Code example:

 public static int add(int m, int n) {
        return m + n;
    }
    public static double add(double m, double n) {
        return m + n;
    }
    public static double add(double m, double n,double p) {
        return m + n + p;
    }
    public static void main(String[] args) {
        add(1,2);//Call add(int m, int n)
        add(1.5,2.5);//Call add(double m, double n)
        add(1.5,2.5,3.9);//Call add(double m, double n,double p)
    }

be careful:

  1. Method names must be the same.
  2. The parameter list must be different (the number of parameters, the type of parameters and the order of types must be different).
  3. It has nothing to do with whether the return value types are the same. If the return value types are different, it cannot constitute an overload.

For example:

public static int add(int m, int n) {
        return m + n;
    }
    public static double add(int m, int n) {
        return m + n;
    }
    public static void main(String[] args) {
        int a=10;
        int b=20;
        int ret=add(a,b);
        System.out.println(ret);
    }
//Compilation error
java: Already in class Method Methods are defined in add(int,int)
  1. When compiling code, the compiler will deduce the argument type and determine which method to call according to the deduction result.
    Overload method calling principle:
      which overloaded method to call is determined during compilation. At compile time, the compiler deduces the argument types passed. For the above code example:
    Add (10,20) -- the result of -- > deduction: int, int, and then find the add method in the class whose two parameters are of type int.
    Add (1.1,2.2) - -- > the result of the deduction: double,double, and then find the add method with two parameters of double type in the class.
       call if found; If it is not found, the compiler will attempt implicit type conversion. If there is an appropriate method to call after type conversion, the method will be called, otherwise an error will be reported.

2.3 method signature

Two identifiers with the same name cannot be defined in the same scope. For example, two variables with the same name cannot be defined in a method. So why can a method with the same method name be defined in a class?
First introduce a new concept
**Method signature: * * the final name of the method after compilation and modification by the compiler. Specific method: Method full path name + parameter list + return value type to form the complete name of the method.

public static int add(int m, int n) {
        return m + n;
    }
    public static double add(double m, double n) {
        return m + n;
    }

    public static void main(String[] args) {
        add(1,2);
        add(1.5,2.5);
    }

After the above code is compiled, use the javap disassembly tool provided with JDK to view it. The specific operations are as follows:

  1. First compile the project to generate a. class bytecode file.
  2. In the console, go to the directory where the. class you want to view is located.
  3. Enter: javap-v bytecode file name
    Part of bytecode compiled by main method

Description of some special symbols in method signature:

Special charactersdata type
Vvoid
Zboolean
Bbyte
Cchar
Sshort
Iint
Jlong
Ffloat
Ddouble
[Array (starting with [and combined with other special characters, it represents the array of corresponding data type, and several [represent multi-dimensional array)
LReference type, starting with L and ending with; At the end, the middle is the full class name of the reference type

Posted by tmc01 on Wed, 01 Sep 2021 13:53:45 -0700