Java series tutorial day07 -- use of methods

day07 - use of method

Outline:

1,Concept of method
2,Method syntax
3,Method use
4,parameter
5,Return value
6,Classification of methods
7,task

Add Qianqian teacher vx to get the latest information    


1, Concept of method

 

 

1.1 what is a method

Java Method in, similar to functions in other languages, is a piece of code used to complete specific functions. This code can be called and executed multiple times.
Function: function
 method: method


1.2. Why use methods / functions

If a function in the program needs to be executed multiple times, CV Dafa, the code has the following problems:
  1,The code is too bloated!
  2,Poor reading!
  3,Poor maintenance!


1.3 function of method

1,Avoid repeated code and enhance the readability of the program.
2,Improve the maintainability of the program.


2, Method syntax

2.1 use of method

step1: Method declaration is just a method declaration, in which the code of the method is written clearly. But the code does not execute.
step2: Method is called several times, and the code in the method is executed several times.
​


2.2 syntax of method

1.Syntax for declaring a method:
Compare the gourd with the gourd main Function declares a method
public static void main(String[] args){}
/*
public static : Don't ask!!!
void: The return value of a method, void means "empty", which means that the method has no return value.
  Return value: the result returned to the caller after a method is executed. Unfinished to be continued...
main,Method name, which meets the naming convention of identifier.
(),Is a sign of the method.
Parameter: to be continued..
{},The code inside is the method body.
*/
​
2.Syntax format of declaration method:
[Modifier 1, Modifier 2...] Return value type method name(Formal parameters){
    Method body;//Code in method
}
​

Note: where is the method declared? Class, other methods. You must not write the declaration of one method in another method.

Example code:

public class Test1Method
{
  
​
​
  public static void main(String[] args){//Program entry, JVM
    /*
    The way is for the dog to roar wherever it needs!!
    Method name
    */
    //1. Requirements 1-10 and
    //Step 2: call method
    getSum();//Call place
​
    System.out.println("Here are other codes.. 10 lines..");
​
    //2. Here we need to find the sum of 1-10
    getSum();//Call place
​
    System.out.println("helloworld...");
​
    //3. It is also necessary to find the sum of 1-10
    getSum();//Call place
​
    System.out.println("main...over...");
  }
​
​
  //Define a method I write -- > for summation, the sum of 1-10
  public static void getSum(){
    int sum = 0;
    for(int i= 1;i <= 20;i++){
      sum += i;
    }
    System.out.println("1-20 And:"+sum);
  }
​
​
​
}

Example code:

public class Test3Method 
{
  //Defines a method for printing a line of split lines
  public static void printLine(){
    for(int i= 0;i<20;i++){
      System.out.print("-");
    }
    System.out.println();
  }
​
​
  public static void main(String[] args) 
  {
    //Print the poem "improved version of quiet night thinking". For each sentence printed, there is a line of dividing line
    System.out.println("The moon shines in front of the window");
    printLine();
    
    System.out.println("It's suspected to be frost on the ground");
    
    printLine();
​
    System.out.println("look at the bright moon");
​
    printLine();
​
    System.out.println("Three pairs of ground shoes");
    
    printLine();
    
  
  }
}
​

3, Method parameters

What are parameters? The external (at the call) incoming data required for the execution of the current method.

  • Formal parameter: it is called formal parameter for short. When a method is declared, it is used to receive external incoming data.
  • Actual parameter: it is called actual parameter for short. When the method is called, the value assigned to the formal parameter is the actual data.

When a method is called, the formal parameters are assigned with actual parameters. This process is called parameter passing. (parameter passing: Argument -- > formal parameter)

1. When designing a method, we need to design several parameters because several values in the method cannot be determined and need to be passed in from the call. Used to separate multiple parameters.
2. When calling a method: Arguments must match formal parameters strictly: arguments are allocated to formal parameters one by one in order. Number, type, order, strict matching.

Example code:

public class Test1Param
{
  //This method is used to find the sum of 1-10
  /*
  Do not declare variables in the method that do not know the specific value as parameters.
​
  Parameters:
    Purpose of formal parameter: it is specially used to receive external incoming data when calling methods
    Argument: the actual value passed to the formal parameter when calling the method.
  */
  public static void getSum(int n){//Formal parameter
    int sum = 0;//Local variable: must be assigned to use
    
    for(int i= 1;i <= n;i++){
      sum += i;
    }
    System.out.println("1-"+ n +"And:"+sum);
  }
​
​
  public static void main(String[] args){//JVM Auto
    //Sum, sum of 1-10
    getSum(10);//Actual parameters
    //. . . 
​
    //Sum, sum of 1-20
​
    getSum(20);//n=20
​
    //...
    //Sum, sum of 1-100
    getSum(100);//n=100
  }
}

When a method is called, the arguments must strictly match the formal parameters. Example code:

public class Test2Param 
{
  //This method is used to compare the size of two int numbers
  public static void compare(int a,int b){
    System.out.println(a);
    System.out.println(b);
    if(a > b){
      System.out.println(a + " > " + b);
    }else if(a < b){
      System.out.println(a + " < " + b);
    }else{
      System.out.println(a + " = " + b);
    }
  }
​
  //Test parameters:
  public static void test1(int a,double b,String c){
    System.out.println("a:"+a);
    System.out.println("b:"+b);
    System.out.println("c:"+c);
  }
​
​
  public static void test2(){
    for(int i= 1;i<=10;i++){
      System.out.println("hello world. . ");
    }
  }
​
  public static void main(String[] args) 
  {
    //Class exercise: design a method to compare the size of two numbers
  
    compare(5,10);
​
    test1(10,"haha",3.14);
    System.out.println("Hello World!");
  }
}
​


4, Method

1,What is return value?
    Return value: indicates the result to be returned to the caller after a method is executed. You need to declare a variable at the call to receive the result.
    
Notes on return value:
    A: A method may or may not have a return value.
        If yes, the type of the return value should be clearly written when declaring the method. If there is no return value, it should be written void(Empty). 
    
    public static return type/void Method name(Formal parameters){
        Method body;
    }
    B: If a method has a return value, only one can be returned.
    C: If a method declares a return value, in the method, you must use return Statement returns a value.
    
​


4.1. return statement

Meaning: "return"

return Statements serve two purposes
1,Returns the result of a method to the caller.
2,End the execution of the method.

Example code:

class Test3Return 
{
  //When declaring a method, you need to write clearly the return value of the method and write what type it is,
  //If the method does not return a value, write void
  public static int getSum(){
    int sum = 0;
    for(int i=1;i<=10;i++){
      sum += i;
    }
    return sum;//Pass the value of sum to the calling place of the method
  }
​
  public static void main(String[] args) 
  {
    //A method has a return value. For example, design a method to find the sum of 1-10. You need to print the results in main.
    int res = getSum();//Equivalent to int res = sum
​
    System.out.println("1-10 And:" + res);//55
​
    System.out.println(getSum());//55
​
​
​
  }
}
​


Note on return statement:

A: If a method declares a return value, it must be used in the method return Keyword returns the result to the caller.
B: If a method declares that it has a return value, if there are branches, loop statements, etc. in the method, ensure that no matter which branch is executed, there must be a return value return Statements can be executed to.
C: If a method declares a return value, then return The value after must be consistent with the declared data type.(Automatic transformation)
D: A method can also be used if it does not return a value return Statement to end the execution of the method.
E: Habitually return There are no statements after.

Example code:

class Test4Return 
{
  //1. If the method declaration has a return value, there must be a return statement in the method to return the result.
  public static int test1(){
    return 1;
​
  }
​
  //2. The return value type declared on the method should match the type of the actual returned value.
  //But include compatible types that can be automatically transformed
  //int:byte,short,char,int
  //double:byte,short,char,int,long,float,double
  public static byte test2(){
    int b1 = 3;
    return (byte)b1;
  }
​
  public static int test3(){
    return 1;//Return data, end method
    //return 2;// Inaccessible statement
    
  }
  //If there is no return value in a method, use return to end the method.
  public static void test4(){
    int age = -30;
    if(age < 0){
      return ;
    }
    System.out.println(age);
  }
  
  public static int test5(){
    int age = -30;
    if(age > 0){//Branch, loop -- > see condition
      return age;
    }else{
      return 0;
    }
  }
​
  public static void test6(){
    for(int i=1;i<=10;i++){
      if(i==5){
        //break;// The loop ends and the code continues down..
        return;//End the execution of this method..
      }
      System.out.println(i);
    }
    System.out.println("test6...over...");
  }
​
  //Think about whether the test7 code is wrong?
  public static int test7(){
    for(int i= 1;i<=10;i++){
      return i;
    }
  }
  
  public static void main(String[] args) 
  {
    //System.out.println(test5());
​
    test6();
    
  }
}
​


4.2 classification of methods

1.Methods with no parameters and no return value:
public static void methodName(){
​
}
2.Methods with parameters and no return value:
public static void methodName(Formal parameters){
    
}
3.Method with return value without parameter:
public static returnType methodName(){
    
}
4.Methods with parameters and return values:
public static returnType methodName(Formal parameters){
    
}


5, Recursive method

Recursion: English word: recursion

function/Method, call?
Method can be called where necessary.
You can call another method in one method.
You can also call yourself in a method. Recursive method.

Possible problems: Exception in thread "main" java.lang.StackOverflowError, stack space overflow exception.

  • Method calls itself
  • There should be an exit, gradually close to the exit


Example code:

public class Test1Recursion
{
  
  //Recursive Method 
  public static int getSum(int n){
    System.out.println("******");
    if(n == 1){
      return 1;
    }else{
      return getSum(n - 1) + n;
    }
  }
​
​
  public static void main(String[] args){
    /*
    Find the sum of 1-5:
      +1+2+3+4+5  
​
​
      +1+2+3+4    +5
​
​
    Find the sum of 1-N: getSum(n). This method is used to find the sum of 1-n.
​
           getSum(5)
​
           : getSum(4) + 5
​
             : getSum(3) + 4
​
​
              :getSum(2) + 3
​
​
                getSum(1) + 2
​
                  
                  1
​
    */
​
    int res = getSum(5);
    System.out.println(res);
​
    Scanner sc = new Scanner(System.in);
​
    int num = sc.nextInt();
  }
}

Welfare at the end of the article
You can add teachers vx to get the latest information

  Don't forget to scan the code and get the [Java HD roadmap] and [full set of learning videos and supporting materials]

Keywords: Java JavaEE Back-end

Added by Jeannie109 on Fri, 29 Oct 2021 08:23:25 +0300