Java learning notes - Methods

Posted by Ludo Lambrechts on Sun, 06 Mar 2022 07:26:59 +0100

1, Method overview

Not to mention what the method is, let's look at the code and analyze where the program has shortcomings and how to improve it.

  • Do not use method
        int x = 10;
        int y = 20;
        System.out.println(x+"+"+y+"="+(x+y));
        System.out.println(x+"+"+y+"="+(x-y));

        int x1 = 100;
        int y1 = 200;
        System.out.println(x1+"+"+y1+"="+(x1+y1));
        System.out.println(x1+"+"+y1+"="+(x1-y1));

        int x2 = 1000;
        int y2 = 2000;
        System.out.println(x2+"+"+y2+"="+(x2+y2));
        System.out.println(x2+"+"+y2+"="+(x2-y2));
  • usage method
public class test01 {
    public static void main(String[] args) {
        //Call the summation method to calculate the sum of 10 and 20
        sumInt(10,20);
        //Call the summation method to calculate the sum of 666 and 888
        sumInt(666,888);
        //Call the summation method to calculate the sum of 888 and 999
        sumInt(888,999);

    }
    public static void sumInt(int a, int b){
        int c = a + b;
        System.out.println(a+"+"+b+"="+c);
    }
}
  • Principle of using method and not using method:

    It can be seen from the above programs and pictures that the method is an ordinary code, and this code can complete a specific function and can be repeatedly called or used.

2, Use of methods

The syntax format of defining / declaring methods is shown in the figure:

  • [modifier list]: uniformly written as public static

  • Return value type: any data type in the Java language, including basic data types and all reference data types. If a method is not ready to return any data after execution, the return value type must be written to void.

  • Types of return values: byte, short, int, long, float, double, char, String, void, etc.

  • Method name: the first letter of the method name is lowercase, and the first letter of each subsequent word is capitalized. Follow the hump naming method. See the meaning of the name, such as login, getUsername, getPassword, etc

  • Formal parameter list: (int a,int b) abbreviated as formal parameter. Each formal parameter is a local variable.

  • Method body: using parentheses after formal parameters is the method body. The method body is the core code of full function. The code in the method body only follows the order from top to bottom, and cannot jump to execution.

  • Method call: the calling method format is in advance. The modifier list of the method has the static keyword.

  • About arguments: when a method is called, the data actually passed to the method is called actual parameters, which are called arguments for short. Java syntax stipulates that arguments and formal parameters must correspond, for example: formal parameters (int a,int b) corresponding to arguments (10,20)

3, Return value of method

Each method is to complete a specific function, such as login function and summation function. Since it is a function, there will be a result in most cases after the function is completed, such as login success or failure (true/false), and the final result after summation is 100 or 200, etc.

4, During method execution

What are the common data structures? For example: stack, queue, linked list, array, tree, graph, heap, hash table, etc. Now let's learn about the stack data structure, which is a very simple data structure.

Stack, which is a linear table with limited operation. The limitation is that insertion and deletion operations are only allowed at one end of the table. This end is called the top of the stack, and the other end is called the bottom of the stack. Inserting a new element into a stack is also called stack entry, stack entry or push. It puts the new element above the top element of the stack to make it a new top element; Deleting an element from a stack is also called out of stack, out of stack or pop. It deletes the top element of the stack and makes its adjacent elements become new top elements.

public class test04 {
    public static void main(String[] args) {
        /*
            Memory analysis of method execution process
                The stack data structure needs to be used in the execution of the method
         */
        /*
            Execute the main method first
            main begin
            m1 begin
            m2 begin
            m2 over
            m1 over
            main over
         */
        System.out.println("main begin");
        m1();
        System.out.println("main over");
    }

    public static void m1(){
        System.out.println("m1 begin");
        m2();
        System.out.println("m1 over");
    }
    public static void m2(){
        System.out.println("m2 begin");
        System.out.println("m2 over");
    }
}

Operation results

  • Memory execution method
    Through the execution results, we know that the main method is called first, but it ends last. Among them, the m2 method is called last, but it ends first. The allocation of memory during the call is to press the stack, and the end is to release the memory and pop the stack.

5, Method overload

Constructor is a special method of a class, which is used to initialize a new object of the class and is called automatically after the object (new operator) is created. Each class in Java has a default constructor and can have more than one constructor.

Java construction method has the following characteristics:

  1. The method name must be the same as the class name
  2. There can be 0, 1 or more parameters
  3. There are no return values, including void
  4. The default return type is the object type itself
  5. Can only be used with the new operator
    public static void main(String[] args) {
        /*
            Method overloading
         */
        int a = 10;
        int b = 10;
        int result =sum(a,b);
        System.out.println(result);

        long a1 = 10L;
        long b1 = 20L;
        long result1 = sum(a1,b1);
        System.out.println(result1);

        double a2 = 10.0;
        double b2 = 20.0;
        double result2 = sum(a1,b2);
        System.out.println(result2);
    }


    /*
        Method name: duplicate is not allowed
        Except for method overloading

        For the design of method overloading, the name of the method must be the same
        Grammar is regular

        The following three conditions need to be met to constitute method overloading:
        (1)In the same class
        (2)Same method name
        (3)Different parameter lists, different numbers, different orders, and different types are different
     */



    public static int sum(int a,int b){
        System.out.println("1--------------------");
        return a+b;
    }
    public static long sum(long a,long b){
        System.out.println("2--------------------");
        return a+b;
    }
    public static double sum(double a,double b){
        System.out.println("3--------------------");
        return a+b;
    }
}

Operation results

6, Method recursion

Method recursion means that the method calls itself.

public class test06 {
    public static void main(String[] args) {
        /*
            Method recursion
                Method itself, call itself
         */
        m();
    }
    public static void m(){
        System.out.println("123");
        m();
    }
}

java.lang.StackOverflowError. This error is a stack memory overflow error. After the error occurs, the JVM exits and the program ends. In fact, the above code calls the m() method during the execution of the m() method, and the method itself calls itself, which is the method recursive call.

Topics: Java JavaEE