Java methods and arrays

Java Procedure

summary

  • The method is an orderly combination of steps to solve a class of problems
  • Methods are contained in classes or objects
  • Methods are created in the program and referenced elsewhere
  • The design principle of the method is that the method can only complete one function, which is conducive to the later expansion

Composition of method

Method contains a method header and a method body

  • Modifier: the modifier is optional and tells the compiler how to call the method
  • Return value type: a method may return a value. returnValueType is the type of the return value of the method. Some methods perform the required operations, but if there is no return value, the returnValueType keyword is void
  • Method name: is the actual name of the method
  • Parameter type: a parameter is like a placeholder. When a method is called, it passes a value to the parameter. This value is called an argument or variable. The parameter list refers to the parameter type, order and number of parameters of the method. Sweet potato is optional, and the method may not contain parameters
    1. Formal parameters: receive external input data when the method is called
    2. Argument: the data actually passed to the method when the method is called
  • Method body: the method body contains specific statements that define the function of the method
package com.zedhz.method;

public class Demo02 {
    public static void main(String[] args) {
        int max = max(123,53);
        System.out.println(max);

    }

    //Specific size
    public static int max(int num1,int num2){

        int result = 0;

        if (num1==num2){
            System.out.println("num1==num2");
            return 0; //Termination method
        }

        if (num1>num2){
            result = num1;
        }else {
            result = num2;
        }

        return result;
    }
}

Method overload

  • Method names must be the same
  • The parameter list must be different (different numbers or types, different order of parameters)
  • The return types of methods can be the same or different
  • Only different return types are not enough to constitute a method overload
  • If the method names are the same, the compiler will match them 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

Variable parameters

  • In the method declaration, add an ellipsis after specifying the parameter type
  • Only one variable parameter can be specified in a method. It must be the last parameter of the method, and any ordinary parameter must be declared before it
  • The variable parameter definition type can only be the current type
package com.zedhz.method;

public class Demo03 {
    public static void main(String[] args) {
        Demo03 demo03 = new Demo03();
        demo03.test(2,2,3);
    }

    //It must be the last parameter of the method, and any ordinary parameter must be declared before it
    public void  test(int x,int... i){

        //How many values are taken by the array subscript
        System.out.println(i[0]);
    }
}

recursion

Recursion is calling itself, which consists of two parts

  1. Recursive header: when not to call its own method. If there is no header, it will enter an endless loop
  2. Recursive body: when do I need to call my own method
package com.zedhz.method;

public class Demo05 {
    public static void main(String[] args) {

        System.out.println(f(100));

    }
    //5!  5*4*3*2*1
    //4!  4*3*2*1
    //3!  3*2*1
    //2!  2*1
    //1!  1*1
    public static int f(int n){
        if (n==1){
            return 1;
        }else {
            return n*f(n-1);
        }
    }
}

array

Array is an ordered collection of data of the same type. Each data takes an array element. Each element can access them through subscript. The first subscript of the array is 0

Array declaration creation

  • Array variables must be declared. The syntax for declaring array variables is as follows:

  • datatype[] arrayRefVar //Preferred method
    dataType arrayRefVar[] //Same effect, but not preferred
    
  • The syntax for creating an array with the new operator is as follows

  • dataType[] arrayRefVar = new dataType[arraySize];
    
    int[] nums; //Declare an array
    nums = new int[10]; //Create an array of 10 lengths
    
  • The elements of the array are accessed by index. The default is 0 subscript

  • arrays.length //Get array length
    

Initialization of array

  1. initiate static

    • int[] a = {1,2,3};
      Man[] mans = {new Man(1,1),new Man()2,2};
      
  2. dynamic initialization

    • int[] a = new int[2];
      a[0] = 1;
      a[1] = 2;
      
  3. Default initialization

    • Array is a reference type, and its elements are equivalent to instance variables. Therefore, once the array is allocated space, each element in it is implicitly initialized in the same way as instance variables

Memory analysis

  • Heap:

    new objects and arrays

    It can be shared by all threads without storing other object references

  • Stack:

    Store the basic variable type (it will contain the specific value of this basic type)

    The variable of the reference object (the specific address of the reference in the heap will be stored)

  • Method area:

    Can be shared by all threads

    Contains all class and static variables

Use of arrays

  • Normal For loop
  • For each loop
  • Array as method input parameter
  • Array as return value
package com.zedhz.array;

public class Demo04 {
    public static void main(String[] args) {
        int[] arrays = {1,2,3,4,5,6,7,8,9,10};

        //No subscript
//        for (int array : arrays) {
//            System.out.println(array);
//
//        }

        printArray(arrays);
        System.out.println("============================");
        int[] reverse = reverse(arrays);
        printArray(reverse);
        System.out.println("=============================");

        sumArrays(arrays);
    }

    //Print array elements
    public static void printArray(int[] arrays){
        for (int i = 0; i < arrays.length; i++) {
            System.out.print(arrays[i] + "  ");
        }
    }


    //Calculates the sum of array elements
    public static void  sumArrays(int[] arrays){
            int sum = 0;
        for (int i = 0; i < arrays.length; i++) {
            sum+=arrays[i];
        }
        System.out.println(sum);
    }

    //Invert array
    public static int[] reverse(int[] arrays){
        int[] result = new int[arrays.length];

        for (int i = 0,j = arrays.length -1; i < arrays.length; i++,j--) {
            result[j] = arrays[i];
        }

        return result;
    }
}

Multidimensional array

You can see arrays as arrays and nested arrays in arrays

Two dimensional array

  • int a[][] = new int[2][5];
    

Gets the value of a two-dimensional array

package com.zedhz.method;

public class Demo07 {

    public static void main(String[] args) {
        /**
         * 1,2 arrays[0]
         * 2,3 arrays[1]
         * 3,4 arrays[2]
         * 4,5 arrays[3]
         */
        int[][] arrays = {{1,2},{2,3},{3,4},{4,5}};
        System.out.println(arrays[0][0]);
    }


}

Arrays class

  • Array tool class java util. Arrays
  • The array utility class allows us to perform some basic operations on data objects
  • The methods in the Arrays class are static methods decorated with static. When used, they can be called directly using the class name instead of using objects

Common functions of Arrays class

  • Assign value to array: fill method
  • Sort array: sort method, in ascending order
  • Compare arrays: the equals method compares whether the values of array elements are equal
  • Find array elements: the binarySearch method can perform binary search on the sorted array

Bubble sorting

  • Compare two adjacent elements in the array. If the first number is larger than the second, exchange their positions
  • Each comparison produces a maximum or minimum number
  • In the next round, you can reduce one cycle
  • Cycle successively until the end
package com.zedhz.array;

import java.util.Arrays;

public class Demo07 {
    public static void main(String[] args) {
        int[] array = {5,7,0,1,2,6};

        int[] sort = sort(array);
        System.out.println(Arrays.toString(sort));

    }

    public static int[] sort(int[] array){

        int temp = 0;
        //How many times does the outer circle have to go
        for (int i = 0; i < array.length-1; i++) {
            //The inner loop judges two values. If the first number is greater than the first number, the position is exchanged
            for (int j = 0; j < array.length-i-1; j++) {
                if (array[j]>array[j+1]) {
                    temp = array[j+1];
                    array[j+1] = array[j];
                    array[j] = temp;
                }
            }
        }
        return array;
    }
}

Keywords: Java

Added by Flyier on Mon, 03 Jan 2022 06:33:14 +0200