JAVA Notes 3. Use of methods

1. Basic usage of methods

1.1. What is the method
1. The method is a code snippet, similar to "function" in C.
2. Definition of method: code snippets can be reused. (Reuse)
3. Significance of the method:
*Modular organization code (when code size is more complex)
* Make the code reusable, so that a single code can be used in multiple locations.
* Make code easier to understand and understand
*Call existing method development directly without having to repeat wheel building
1.2. Method Definition Semantics
1. 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(Arguments...);

Example: Define a method to add two integers

public class Class1 {
    public static void main(String[] args) {
      int a=10;
      int b=20;
      //Call to method
        int ret=add(a,b);
        System.out.println("ret="+ret);
    }
    //Definition of method
    public static int add(int x, int y) {
        return  x + y;
    }
}
//Execution result ret=30

2. Notes:
*The two keywords public and static have specific meanings and will not be discussed for now, but will be described in more detail later.
* When a method is defined, parameters may not exist, and each parameter specifies a type.
* When a method is defined, the return value can also be nonexistent, and if there is no return value, the return value type should be written as void.
*Parameters at method definition are called formal parameters, and parameters at method call are called arguments.
*Method definitions must be in a class, and the location of the method to be called can be before or after the method definition.
* In java, there are no methods to declare concepts. (Define a method, you must have a method body to implement {})
1.3 Execution of method calls
1. Basic Rules:
*When defining a method, the code for the method is not executed, meaning it is executed when called.
* When a method is called, arguments are assigned to the parameter.
* Once the parameter is passed, the method body code is executed.
*When method 1 finishes executing (a return statement is encountered), it finishes execution, returns to the method call location and continues execution.
*A method can be called multiple times.
Example: Calculate 1!+ 2!+ 3!+ 4!+ 5!

public class Class1 {
    public static void main(String[] args) {
     int sum=0;
     //1!+2!+3!+4!+5!
     for(int i=1;i<=5;i++){
     int temp=0;
     //Factorial value of current i
     temp=factor(i);
     sum+=temp;
     }
        System.out.println(sum);
    }

    /**
     * This method is used to calculate the factorial of the incoming value n
     * @param n Factor to be calculated
     * @return n Factorial value of
     */
    public static int factor(int n){
        int ret=1;
        for(int i=1;i<=n;i++){
            ret*=i;
        }
        return ret;
    }
}
//Execution results: 153

Return value of 1.4 method
A method may or may not have a return value. Judging from the current role of this method.
When there is no return value, we use void to declare the method.
When return is used in a method that does not have a return value; Indicates that the current method ends the call, and subsequent code is no longer executed.

public class test {
    public static void main(String[] args) {
        int num=6;
        fun(num);
    }
     public  static void fun(int num) {
        if(num%3==0){
            System.out.println("num Is a multiple of three");
            return;
        }
         System.out.println("hehe");
    }
}
//Write return; num is a multiple of three
//No return was written; The result is that num is a multiple of three hehe 

1.5 Relationship between Arguments and Formal Parameters
Parameter Passing in Java Only Value Passing
Example: Swap 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;
}
}
// Run result a = 10 b = 20

Reason analysis: The code just now did not complete the data exchange. For the base type, a parameter is a copy of an argument. That is, call by value

Solution: Pass a reference type parameter (such as an array to solve this problem) or a value pass!

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;
}
}
// Run result a = 20 b = 10

2. Overload of methods

1. Method overload is different from method override. Method overloading can be used when we need to use a function that is compatible with multiple parameters at the same time.
2. Method overload (don't look at return values): different methods that occur in the same class.
3. Method overloads represent a set of methods with identical method names, different number or types of parameters, and have nothing to do with method return values!!! The return value type of the method does not affect the overload.
Example:

public class test {
    public static void main(String[] args) {
        int a=6;
        int b=20;
        int sum=add(a,b);
        System.out.println(sum);

        int a1=9;
        int b1=1;
        int c1=12;
        int sum1=add(a1,b1,c1);
        System.out.println(sum1);

        double a2=1;
        double  b2=2;
        double c2=12;
        double sum2=add(a2,b2,c2);
        System.out.println(sum2);
    }

    private static int add(int a, int b) {
        return a+b;
    }
    //Overloading methods
    private static int add(int a1, int b1, int c1) {
        return a1+b1+c1;
    }
    //Overloading methods
    private static double add(double a2, double b2, double c2) {
        return a2+b2+c2;
    }
}

4. Method overload does not occur when two methods have the same name and the same parameters but different return values.
(The two methods in the code below have the same name and parameters, but return value types are int and double, compilation error)

5. The reason why all println parameters can be passed is that some column overload methods are defined.

3. Method Recursion

Method Recursion: Program structure, which is fundamental in the data results and algorithm sections
Data structure: how data is stored is the data structure
Algorithms: How data is handled is called algorithms
1.1 Recursion concept
A method that calls itself during execution is called recursion. (Be sure to pay attention to the semantics of method recursion!!! That is, what this method can do without thinking about how it is implemented internally in the program)
Delivery: The process of splitting a large problem into subproblems
Return: Return values are successively given when termination conditions are encountered (the sub-problem has a solution process)
1.2 What scenarios can recursion be used:
*A big problem can be broken down into subproblems
*The original problem and the subproblem have the same solution except for the different data sizes
*There is a recursive termination condition
Example: 5!

public class test {
    public static void main(String[] args) {
        int num=5;
        System.out.println(factor(5));
    }
    //Write a recursive function to implement 5!
public static int factor(int num){
    //Write Termination Conditions First
    if (num==1){
        return num;
    }
    return num*factor(num-1);
}
}

1.3 About Call Stack

When a method is called, there is a memory space such as a "stack" that describes the current call relationship. Call stack.
Each method call is referred to as a "stack frame", and each stack frame contains information such as which parameters of the call are and where to go back to continue execution. Later, with IDEA, we can easily see the contents of the call stack.
1.4 Recursive Practice
Example 1: Print each digit in sequence. For example 1234 prints out 1 2 3 4

 public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter a number:");
        int n = scanner.nextInt();
        print(n);
    }
    public static void print(int n) {
        if (n < 0) {//When you enter a negative number, first turn it into an integer.
            System.out.println("-");
            n = -n;
        }
        if (n > 9) {
            print(n / 10);//recursion
        }
        System.out.print(n % 10+" ");//Print digits
    }

Example 2: Recursive 1+2+3+. + 10

public static void main(String[] args) {
        System.out.println(add(10));
    }
    public static int add(int n) {
    if(n==1){
        return n;
    }
    return n+add(n-1);
    }

Example 3: Write a recursive method, enter a non-negative integer, and return the sum of the numbers that make up it. For example, if you enter 1729, you should return 1+7+2+9, and its sum is 19

  public static void main(String[] args) {
        System.out.println(sum(1729));
    }
    public static int sum(int n) {
        //boundary
   if(n<10){
       return n;
   }
   return n%10 + sum(n/10);
    }

Example 4: N term of the Chopponacci series (1 1 12 3 5 8 13 21 34...)

 public static void main(String[] args) {
        System.out.print(fib(5));
    }
    public static int fib(int n) {
        //boundary
   if(n==1||n==2){
       return 1;
   }
   return fib(n-1)+fib(n-2);
    }

When we asked for fib(40), we found that the program was executing very slowly. The reason is a lot of repetition

class Test {
public static int count = 0; // This is a member variable of the class. This will be described in more detail later.
public static void main(String[] args) {
System.out.println(fib(40));
System.out.println(count);
}
public static int fib(int n) {
if (n == 1 || n == 2) {
return 1;
}
if (n == 3) {
count++;
}
return fib(n - 1) + fib(n - 2);
}
}
// results of enforcement
102334155
39088169 // fib(3) executed 30 million times

By example 4, we find that recursion is less efficient because it contains a lot of repetitive operations. Dynamic return is the solution to recursive duplicate computation.
The Fibonacci sequence problem can be solved in a circular manner to avoid redundant operations.

   public static void main(String[] args) {
            System.out.println(fib(40));
        }
    public static int fib(int n) {
        int last2 = 1;
        int last1 = 1;
        int cur = 0;
        for (int i = 3; i <= n; i++) {
            cur = last1 + last2;
            last2 = last1;
            last1 = cur;
        }
        return cur;
    }

Iteration (looping) is more efficient than recursion, which is less efficient, but recursion is better written.
1.5 Recursive Summary
*Recursion is an important way to solve programming problems.
*Some problems are naturally defined recursively (e.g., Fibonacci series, binary trees, etc.) and can be easily solved using recursion.
*Some problems can be solved using recursion and using non-recursion (loops). Loops are more recommended at this point, and non-recursive programs are more efficient than recursive programs.

Keywords: Java

Added by Killswitch on Mon, 07 Feb 2022 19:34:57 +0200