Use of method-05

1. method

1.1 concept of method

method is a code set that organizes code blocks with independent functions into a whole and makes them have special functions

  • Be careful:
    • Method must be created before it can be used. This process becomes method definition
    • Method can not be run directly after creation. It needs to be used manually before execution. This process becomes a method call

2. Method definition and call

2.1 parameterless method definition and call

  • Definition format:

    public static void method name (){
    	//Method body;
    }
    
  • Example:

    public static void method (    ) {
    	// Method body;
    }
    
  • Call format:

    Method name ();
    
  • Example:

    method();
    
  • Be careful:
    The method must first be defined, then called, otherwise the program will report errors.

2.2 method calling procedure

When each method is called for execution, it will enter the stack memory and have its own independent memory space. After the internal code of the method is called, it will pop the stack from the stack memory and disappear.

2.3 practice of nonparametric method (application)

  • Requirement: design a method to print the larger of two numbers
  • Train of thought:
    • ① Define a method to print the larger of two numbers, such as getMax()
    • ② Method to save two numbers
    • ③ Using branch statements to deal with the size relationship of two numbers in two cases
    • (4) calling a well-defined method in the main() method.
  • Code:
public class MethodTest {
    public static void main(String[] args) {
        //Invoke a well-defined method in the main() method.
        getMax();
    }

    //Define a method to print the larger of two numbers, such as getMax()
    public static void getMax() {
        //Method to save two numbers
        int a = 10;
        int b = 20;

        //Using branch statements to deal with the size relationship of two numbers in two cases
        if(a > b) {
            System.out.println(a);
        } else {
            System.out.println(b);
        }
    }
}

3. Method definition and call with parameters

3.1 method definition and call with parameters (Master)

  • Definition format:
    Parameters: consists of data type and variable name - data type variable name
    Parameter example: int a
    public static void method name (parameter 1){
    	Method body;
    }
    public static void method name (parameter 1, parameter 2, parameter 3...){
    	Method body;
    }
    
  • Example:
    public static void isEvenNumber(int number){
        ...
    }
    public static void getMax(int num1, int num2){
        ...
    }
    
    • Be careful:
      When defining a method, neither the data type nor the variable name in the parameter can be missing. If any program is missing, an error will be reported
      When defining a method, multiple parameters are separated by commas (,)
      
  • Call format:
    Method name (parameter);
    Method name (parameter 1, parameter 2);
    
  • Example:
    isEvenNumber(10);
    getMax(10,20);
    
    • When a method is called, the number and type of parameters must match the settings in the method definition, otherwise the program will report an error

3.2 formal and actual parameters (understanding)

  1. Formal parameters: parameters in method definitions
    Equivalent to variable definition format, for example: int number
  2. Arguments: arguments in method calls
    Equivalent to using a variable or constant, for example: 10 number

3.3 practice with parameters (application)

  • Requirement: a method is designed to print the larger of the two numbers. The data comes from the method parameter}
  • Train of thought:
    • ① Define a method to print the larger of two numbers, such as getMax()
    • ② Define two parameters for the method to receive two numbers
    • ③ Using branch statements to deal with the size relationship of two numbers in two cases
    • (4) calling the defined method (using constant) in the main() method.
    • In the main() method, call the defined method (using variables).
  • Code:
public class MethodTest {
    public static void main(String[] args) {
        //In the main() method, we call the defined method (using constant).
        getMax(10,20);
        //When you call a method, you can give it as many as others want. You can give it as many types as others want
        //getMax(30);
        //getMax(10.0,20.0);

        //In the main() method, we call the defined method (using variables).
        int a = 10;
        int b = 20;
        getMax(a, b);
    }

    //Define a method to print the larger of two numbers, such as getMax()
    //Define two parameters for the method to receive two numbers
    public static void getMax(int a, int b) {
        //Using branch statements to deal with the size relationship of two numbers in two cases
        if(a > b) {
            System.out.println(a);
        } else {
            System.out.println(b);
        }
    }
}

4. Definition and call of method with return value

4.1 method definition and call with return value

  • Definition format

    public static data type method name (parameter){ 
    	return data;
    }
    
  • Example

    public static boolean isEvenNumber( int number ) {           
    	return true ;
    }
    public static int getMax( int a, int b ) {
    	return  100 ;
    }
    
    • Be careful:
      • When defining a method, the return value after return should match the data type on the method definition. Otherwise, the program will report an error
  • Invocation format

    Method name (parameter);
    Data type variable name = method name (parameter);
    
  • Example

    isEvenNumber ( 5 ) ;
    boolean  flag =  isEvenNumber ( 5 ); 
    
    • Be careful:
      • The return value of the method is usually received with a variable, otherwise the return value will be meaningless

4.2 practice with return value

  • Requirement: design a method to obtain the larger value of two numbers, and the data comes from the parameters

  • Train of thought:

    • ① Define a method to get the larger of two numbers
    • ② Using branch statements to deal with the size relationship of two numbers in two cases
    • ③ Set the corresponding return results in two cases according to the question settings
    • (4) calling the defined method in main() method and saving it with variables.
    • In the main() method, call the defined method and print the result directly.
  • Code:

    public class MethodTest {
        public static void main(String[] args) {
            //In the main() method, we call the defined method and use variable preservation.
            int result = getMax(10,20);
            System.out.println(result);
            //In the main() method, call the defined method and print the result directly.
            System.out.println(getMax(10,20));
        }
        //Define a method to get the larger of two numbers
        public static int getMax(int a, int b) {
            //Using branch statements to deal with the size relationship of two numbers in two cases
            //Set the corresponding return results in two cases according to the question settings
            if(a > b) {
                return a;
            } else {
                return b;
            }
        }
    }
    
    

5. Method precautions

5.1 method precautions

  • Method cannot be nested

    • Example code:

      public class MethodDemo {
          public static void main(String[] args) {
      
          }
      
          public static void methodOne() {
      		public static void methodTwo() {
             		// Compilation error will be raised here!!!
          	}
          }
      }
      
      
  • void means there is no return value. You can omit return or write return separately without data

    • Example code:

      public class MethodDemo {
          public static void main(String[] args) {
      
          }
          public static void methodTwo() {
              //return 100; compilation error because there is no specific return value type
              return;	
              //System.out.println(100); return statement cannot be followed by data or code
          }
      }
      
      

5.2 general format of the method

  • Format:

    public static return value type method name (parameter){
       Method body; 
       return data;
    }
    
    
  • Interpretation:

    • public static modifier, remember this format first
      Return value type the data type of the data returned after the method operation
      If the method operation is completed and no data is returned, void is written here, and return is generally not written in the method body
      Method name: the identifier used when calling the method
      Parameter: it consists of data type and variable name. Multiple parameters are separated by commas
      Method body: code block to complete the function
      Return: if the method operation is completed, data is returned, which is used to return data to the caller
  • When defining a method, two things should be clear

    • Specify the return value type: it is mainly to determine whether there is data return after the method operation is completed. If not, write void; if yes, write the corresponding data type
    • Clear parameters: mainly clear the type and quantity of parameters
  • Note when calling method:

    • The method of void type can be called directly
    • Method of non void type, variable is recommended to receive calls

6. Method overload

6.1 method overload

  • Method overload concept
    Method overloading refers to the relationship between multiple methods defined in the same class, and multiple methods meeting the following conditions constitute overloading each other

    • Multiple methods in the same class
    • Multiple methods have the same method name
    • Multiple methods have different parameters, types or quantities
  • Be careful:

    • Overload only corresponds to the definition of the method, independent of the method call, and the call method refers to the standard format
    • Overloads are only used to identify the names and parameters of methods in the same class, regardless of the return value. In other words, the return value cannot be used to determine whether two methods constitute overloads
  • Correct example:

    public class MethodDemo {
    	public static void fn(int a) {
        	//Method body
        }
        public static int fn(double a) {
        	//Method body
        }
    }
    public class MethodDemo {
    	public static float fn(int a) {
        	//Method body
        }
        public static int fn(int a , int b) {
        	//Method body
        }
    }
    
    
  • Error example:

    public class MethodDemo {
    	public static void fn(int a) {
        	//Method body
        }
        public static int fn(int a) { 	/*Error reason: overload has nothing to do with return value*/
        	//Method body
        }
    }
    public class MethodDemo01 {
        public static void fn(int a) {
            //Method body
        }
    } 
    public class MethodDemo02 {
        public static int fn(double a) { /*Error reason: These are two fn methods of two classes*/
            //Method body
        }
    }
    

6.2 method heavy load exercise (mastery)

  • Requirement: use the idea of method overloading to design a method to compare whether two integers are the same, which is compatible with all integer types (byte,short,int,long)

  • Train of thought:

    • ① Define the method compare() to compare two numbers. Select two int type parameters
    • ② Define the corresponding overload method, change the corresponding parameter type, and change the parameter to two long parameters
    • ③ Define all overloaded methods, two byte types and two short type parameters
    • ④ Complete method call, test run results
  • Code:

    public class MethodTest {
        public static void main(String[] args) {
            //Calling method
            System.out.println(compare(10, 20));
            System.out.println(compare((byte) 10, (byte) 20));
            System.out.println(compare((short) 10, (short) 20));
            System.out.println(compare(10L, 20L));
        }
        //int
        public static boolean compare(int a, int b) {
            System.out.println("int");
            return a == b;
        }
    
        //byte
        public static boolean compare(byte a, byte b) {
            System.out.println("byte");
            return a == b;
        }
    
        //short
        public static boolean compare(short a, short b) {
            System.out.println("short");
            return a == b;
        }
    
        //long
        public static boolean compare(long a, long b) {
            System.out.println("long");
            return a == b;
        }
    
    }
    
    

7. Parameter transfer of method

7.1 basic types of method parameter transfer

  • Test code:

    public class ArgsDemo01 {
        public static void main(String[] args) {
            int number = 100;
            System.out.println("call change Before method:" + number);
            change(number);
            System.out.println("call change Methods:" + number);
        }
    
        public static void change(int number) {
            number = 200;
        }
    }
    
    
  • Conclusion:

    • Parameters of basic data type and changes of formal parameters do not affect the actual parameters
  • Conclusion basis:

    • Each method will have its own stack space in the stack memory, and the stack will disappear after the method runs

7.2 method parameter transfer reference type

  • Test code:

    public class ArgsDemo02 {
        public static void main(String[] args) {
            int[] arr = {10, 20, 30};
            System.out.println("call change Before method:" + arr[1]);
            change(arr);
            System.out.println("call change Methods:" + arr[1]);
        }
    
        public static void change(int[] arr) {
            arr[1] = 200;
        }
    }
    
  • Conclusion:

    • For parameter of reference type, the change of formal parameter affects the value of actual parameter
  • Conclusion basis:

    • For the parameter of reference data type, the address value is passed in, which will cause the effect of two references pointing to the same memory in memory. Therefore, even if the method pops the stack, the data in the heap memory is the result of the change

7.3 array traversal

  • Requirement: design a method for array traversal, and the traversal result should be on one line. For example: [11, 22, 33, 44, 55]
  • Train of thought:
    • ① Because the result is required to be output on one line, we need to learn a new output statement System.out.print("content");
      System.out.println("content"); output content and wrap
      System.out.print("content"); output content does not wrap
      System.out.println(); for line wrapping
    • ② Define an array and use static initialization to complete the initialization of array elements
    • ③ Define a method to traverse the array with the general format of array traversal
    • ④ Modify traversal operation with new output statement
    • ⑤ Call traversal method
  • Code:
    public class MethodTest01 {
        public static void main(String[] args) {
            //Define an array and use static initialization to complete the initialization of array elements
            int[] arr = {11, 22, 33, 44, 55};
    
            //Calling method
            printArray(arr);
        }
    
        //Define a method to traverse the array with the general format of array traversal
        /*
            Two clear:
                Return value type: void
                Parameter: int[] arr
         */
        public static void printArray(int[] arr) {
            System.out.print("[");
            for(int x=0; x<arr.length; x++) {
                if(x == arr.length-1) {
                    System.out.print(arr[x]);
                } else {
                    System.out.print(arr[x]+", ");
                }
            }
            System.out.println("]");
        }
    }
    

7.4 array maximum (application)

  • Requirement: design a method to get the maximum value of elements in the array

  • Train of thought:

    • ① Define an array and use static initialization to complete the initialization of array elements
    • ② Define a method to get the maximum value and the maximum value in the array. We have explained it in the array
    • ③ Call to get the maximum value method and receive the return result with variable
    • ④ Output the results to the console
  • Code:

    public class MethodTest02 {
        public static void main(String[] args) {
            //Define an array and use static initialization to complete the initialization of array elements
            int[] arr = {12, 45, 98, 73, 60};
    
            //Call to get the maximum value method and receive the return result with variable
            int number = getMax(arr);
    
            //Output the results to the console
            System.out.println("number:" + number);
        }
    
        //Define a method to get the maximum value in the array
        /*
            Two clear:
                Return value type: int
                Parameter: int[] arr
         */
        public static int getMax(int[] arr) {
            int max = arr[0];
            for(int x=1; x<arr.length; x++) {
                if(arr[x] > max) {
                    max = arr[x];
                }
            }
            return max;
        }
    }
    
Published 6 original articles, won 0 praise and visited 38
Private letter follow

Posted by craigengbrecht on Tue, 11 Feb 2020 05:05:32 -0800