2021-9-1 [radium JAVA] Introduction to JAVA learning - use of methods

Objective of this section: to master the use of understanding methods

1. Basic usage of the method

1-1 what is a method
Method is a code fragment, similar to "function" in C language
Its usefulness lies in:
When faced with large-scale and complex code, it can be effectively organized to turn it into reusable modules, where it needs to be moved. This not only makes the code easier to understand, but also effectively reduces the occurrence of repeated development, directly calls the existing methods, and greatly shortens the time.
For example: calculate 1+ 2!+ 3!+ 4!+ 5!

int sum = 0;
for(int i=1;i<=5;i++){
    int tmp=1;
    for(int j=1;j<=i;j++){
    tmp*=j;
    }
    sum+=tmp;
}
System.out.println("sum="+sum);

Double loops are used in this code, which is easy to make mistakes. Next, you can use this method to optimize the code

1-2 method definition syntax
Basic grammar

//Method definition
public static Method return value method name([Parameter type parameters]){
     Method body code
     [return Return value];
}
//Method call
 Return value variable=Method name (argument...);

Code example

 public static void main(String[] args) {
 int a = 10;
 int b = 20;
        
        // Method call
 int ret = add(a, b);
 System.out.println("ret = " + ret);
 }
    // Definition of method
 public static int add(int x, int y) {
 return x + y;
 }
}
// results of enforcement
ret = 30

matters needing attention

  1. The public and static keywords have specific meanings here. We won't discuss them for the time being. They will be described in detail later
  2. When a method is defined, the parameters may not be. Each parameter must specify a type
  3. When defining a method, the return value can also be null. If there is no return value, the return value type should be written as void
  4. The parameters when a method is defined are called "formal parameters", and the parameters when a method is called are called "arguments"
  5. The method definition must be in the class, and the code can be written above or below the calling position
  6. There is no concept of "function declaration" in Java
    1-3 execution process of method call

Basic rules

  • When defining a method, the code of the method will not be executed. It will only be executed when calling
  • When the method is called, the argument is assigned to the formal parameter
  • After the parameter is passed, it will be executed to the method body code
  • After the method is executed (when a return statement is encountered), it is executed. Return to the method call location and continue to execute
  • A method can be called multiple times

1-4 relationship between arguments and formal parameters (important)
Code example: exchanging two integer variables

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

Cause analysis
The code just now did not complete the data exchange
For the basic type, the formal parameter is equivalent to the copy of the argument, that is, the value passing call, and the modification of X and Y does not affect a and b
Solution: pass reference type parameters (such as array to solve this problem)
The running process of this code will be discussed later

class Test {
 public static void main(String[] args) {
 int[] arr = {10, 20};
 swap(arr);
 System.out.println("a = " + arr[0] + " b = " + arr[1]);
 }
 public static void swap(int[] arr) {
 int tmp = arr[0];
 arr[0] = arr[1];
 arr[1] = tmp;
 }
}
// Operation results
a = 20 b = 10

1-5 methods with no return value
The return value of the method is optional and sometimes not
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);
 }
}

There is no return value

2. Overloading of methods

Sometimes when we need to use a function that is compatible with multiple parameters at the same time, we can use method overloading

2-1 problems to be solved for heavy load
Code example

 class Test{
 public static void main(String[] args) {
 int a = 10;
 int b = 20;
 int ret = add(a, b);
 System.out.println("ret = " + ret);
 double a2 = 10.5;
 double b2 = 20.5;
 double ret2 = add(a2, b2);
 System.out.println("ret2 = " + ret2);
 }
 public static int add(int x, int y) {
 return x + y;
 }
}
// Compilation error
Test.java:13: error: Incompatible types: from double Convert to int There may be losses
                double ret2 = add(a2, b2);
                                  

Because the parameter types do not match, you cannot directly use the existing add method. Should you create code like this?

Code example

class Test {
 public static void main(String[] args) {
 int a = 10;
 int b = 20;
 int ret = addInt(a, b);
 System.out.println("ret = " + ret);
 double a2 = 10.5;
 double b2 = 20.5;
 double ret2 = addDouble(a2, b2);
 System.out.println("ret2 = " + ret2);
 }
 public static int addInt(int x, int y) {
 return x + y;
 }
 public static double addDouble(double x, double y) {
 return x + y;
 }
}

This is correct (for example, Go language does this), but Java thinks that the name addInt is unfriendly, so it's better to call it add directly
2-2 use heavy load
Code example

class Test {
 public static void main(String[] args) {
 int a = 10;
 int b = 20;
 int ret = add(a, b);
 System.out.println("ret = " + ret);
 double a2 = 10.5;
 double b2 = 20.5;
 double ret2 = add(a2, b2);
 System.out.println("ret2 = " + ret2);
 double a3 = 10.5;
 double b3 = 10.5;
 double c3 = 20.5;
 double ret3 = add(a3, b3, c3);
 System.out.println("ret3 = " + ret3);
 }
 public static int add(int x, int y) {
 return x + y;
 }
 public static double add(double x, double y) {
 return x + y;
 }
 public static double add(double x, double y, double z) {
 return x + y + z;
 }
}

The names of the methods are all add. But some add is to calculate the addition of int, and some are double addition; Some calculate the addition of two numbers, others calculate three numbers
Add words
The same method name, which provides different versions of implementations, is called method overloading
2-3 overload rules
For the same class:

  1. Same method name
  2. Method has different parameters (number or type of parameters)
  3. The return value type of the method does not affect overloading
    Code example
class Test {
 public static void main(String[] args) {
 int a = 10;
 int b = 20;
 int ret = add(a, b);
 System.out.println("ret = " + ret);
 }
 public static int add(int x, int y) {
 return x + y;
 }
 public static double add(int x, int y) {
 return x + y;
 }
}
// Compilation error
Test.java:13: error: Already in class Test Methods are defined in add(int,int)
        public static double add(int x, int y) {
                             ^ 1 Errors

When the names of two methods are the same, the parameters are the same, but the return values are different, it does not constitute an overload

3. Method recursion

3-1 concept of recursion
When a method calls itself in the process of execution, it is called recursion.
Recursion is equivalent to mathematical "mathematical induction", with a starting condition and then a recursive formula.
For example, we ask N!
Starting condition: when N = 1, N! This start condition is equivalent to the end condition of recursion
Recursive formula: find n, It's hard to find directly. You can convert the problem into n! = > N * (N-1)!

public static void main(String[] args) {
    int n = 5;
    int ret = factor(n);
    System.out.println("ret = " + ret);
}
public static int factor(int n) {
    if (n == 1) {
        return 1;
   }
    return n * factor(n - 1); // factor calls the function itself
}
// results of enforcement
ret = 120

3-2 recursive execution process analysis
The execution process of a recursive program is not easy to understand. You must first understand the execution process of the method, especially after the method execution is completed, return to the calling position and continue to execute

about "Call stack"
Method call, There will be one "Stack" Such memory space describes the current call relationship. Call stack.
Each method call is called a "Stack frame", What are the parameters of this call contained in each stack frame, Return to where to continue execution and other information.
Later we use IDEA It's easy to see the contents of the call stack

Tags: Java

Posted on Wed, 01 Sep 2021 20:55:19 -0400 by Jaguar