Introduction to Java

1, What is the method

We have used many methods before, such as printout statement system out. Println () is a method, which consists of class + object + method. So what is the method? A Java method is a collection of statements that perform a function together. In my opinion, it is equivalent to the function in JS and the function in C language

  • Method is an ordered combination of steps to solve a class of problems
  • Method is contained in a class or object
  • Methods are created in the program and referenced elsewhere

Design method principle: the original meaning of the method is function block, which is the collection of statement blocks to realize a function. When designing methods, we'd better keep the atomicity of methods, that is, a method only completes one function, which is conducive to our later expansion.

Naming principle: hump naming method is adopted. The first letter of the first word is lowercase and the first letter of other words is uppercase

2, Method definition and call

1. Definition of method

Java methods are similar to functions in other languages. They are code fragments used to complete specific functions. Generally, defining a method includes the following syntax

1.1 method head

  • Modifier: optional. It tells the compiler how to call the method and defines the access type of the method
  • Return value type: the method may have a return value. returnValueType is the data type of the return value of the method. Some methods do not return a value when they perform the required operations. In this case, their returnValueType is the keyword void
  • Method name: is the actual name of the method. The method name and parameter table together constitute the method signature
  • Parameter type: the parameter is like a placeholder. When a method is called, it passes a value to a parameter (parameter), which is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters.
    • Formal parameter (formal parameter): used to receive external input data when called in a method
    • Actual parameter (actual parameter): the data actually passed to the method when calling the method

1.2 method body

The specific statements contained in the method body define the function of the method

Modifier 	return type	Method name(Parameter type	Parameter name) {
    ......
        Method body
    ......
    return	Return value;
}

2. Method call

2.1 calling method

Class name Object name Method name (argument list)

2.2 calling form

  1. Return value: method calls are usually treated as a value for assignment or direct output

    int sum = add(1, 2);//Assign sum the result of adding 1 and 2
    System.out.println(add(1,2));//The result of adding 1 and 2 is printed directly
    
  2. No return value: the method call must be a statement

    printText();	//Call the output Hello World!
    public static void printText() {
        System.out.println('Hello World!');
    }
    

3, Method overload

Overloading is a function with the same function name but different formal parameters in a class. If the method names are the same, the compiler will match one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error. Method overload rules include the following:

  • Method names must be the same
  • The parameter list must be different (not necessarily completely different)
  • Different methods can also return the same type
  • Just because the return value is different is not enough to be an overload of a method
//Method overload
public static void main(String[] args) {
    System.out.println(add(1,2,3,4));
    System.out.println(add(1,2));
}
public static int add(int a, int b) {
    return a+b;
}
public static double add(int a, int b,int c, int d) {
    return a+b+c+d;
}

4, Command line parameters

As an extension, you can understand this part

1. The IDEA tool passes command line parameters

  1. Open IDEA and click Terminal in the lower left corner

  2. Enter the full name of the javac file and compile the Java file into a class file

  3. Return to the src directory (if it is already in this directory, you do not need to return), and enter the java file directory The file name string is passed as a parameter

2. Command line parameter transfer from cmd console

  1. Right click the IEDA file and click Show In Explorer to open the location of the file

  2. Enter cmd before the file path, and then press enter to enter the console under the path

  3. The parameter transfer can be completed by performing the same operations as 3 and 4 points in the command line parameter transfer with the IDEA tool

3. Sample code

//Command line parameters
public static void main(String[] args) {
    for(int i = 0; i < args.length; i++) {
        System.out.println("args[" + i + "]" + ": " + args[i]);
    }
}

5, Variable parameters

At jdk1 Starting from 5, Java supports passing a method with variable parameters of the same type. In the method declaration, an ellipsis (...) is added after the specified parameter type, which is the variable parameter. Only one variable parameter can be specified in a method. It must be the last parameter of the method. Any ordinary parameter must be declared before it.

public int findMaxNum(int... numArr) {
    if(numArr.length == 0) {    //Judge whether there is data incoming
        return -1;
    }
    int max = numArr[0];
    for(int i = 0; i < numArr.length; i++) {
        if(max < numArr[i]) {
            max = numArr[i];
        }
    }
    return max;
}

6, Recursion

  • In essence, it is calling itself. Using recursion, we can use simple programs to solve some complex problems, such as Hanoi Tower, eight queens and so on.

  • It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem. The recursive strategy can describe the multiple repeated calculations required in the problem-solving process with only a small amount of program, which greatly reduces the amount of code of the program. The ability of recursion is to define an infinite set of objects with limited statements.

  • However, it is recommended to minimize unnecessary recursion. When the scale is large, the efficiency of recursion is too low or even can not run, which can not reflect the advantages of recursion.

  • Recursive structure

    • Recursive header: when not to call its own method. This is indispensable, otherwise it will fall into an endless loop, causing stack overflow.
    • Recursive body: when do I need to call my own method
public static void main(String[] args) {
    Demo06_Recursion text = new Demo06_Recursion(); //Declare an object to call a method
    Scanner sc = new Scanner(System.in);            //Declare an object to receive keyboard input data
    int num = sc.nextInt();     //Call the input method in the object to enter an integer
    System.out.println(text.Factorial(num));        //Calling methods within objects
}
/*
	Seeking stratum
*/
public int Factorial(int num) {
    if(num == 1) {  //Recursive header, end condition
        return 1;
    } else {        //Recursive body
        return num*Factorial(num-1);
    }
}

Keywords: Java

Added by gvp16 on Sun, 16 Jan 2022 15:28:11 +0200