Java Foundation & Method

Posted by celavi on Thu, 11 Nov 2021 02:06:04 +0100

Java Foundation & Method

1. Overview of methods

Concepts of the 1.1 Method

A method is a set of code that organizes code blocks with separate functions into a whole and has special functions.

Be careful:

  • A method must be created before it can be used, and the process becomes a method definition
  • The method is not created to run directly. It needs to be used manually before it can be executed and becomes a method call

Purpose of method 1.2

Written methods can be reused.

Features of 1.3 Method

  1. It can be encapsulated in a release and called by a method name
  2. Reduce the amount of code written
  3. Can be reused
  4. Maintenance and modification functions are simple
  5. Access rights can be set

2. Definition and invocation of methods

2.1 Parameterless method definition and invocation

  • Define Format
public static void Method Name ( ) { 
	// Method body; 
}
  • Example
public static void method ( ) { 
	// Method body; 
}
  • Call format:
Method Name();
  • Example:
method();
  • Be careful

Method must be defined before calling, otherwise program will error

2.2 Method Call Process Diagram

public class Demo{
    public static void main(String[] args){
        isEvenNUmber();
    }
    //Define a variable to determine if the data is even
    public static void isEvenNumber(){
        int number=10;
        if(number%2==0){
            System.out.println(true);           
        }else{
            System.out.println(false);           
        }       
    }
}

Summary: When each method is called for execution, it enters the stack memory and has its own separate memory space. After the method internal code is called, it will disappear from the stack memory.

General format for 2.3 methods

  • format
public static Return value type method name(parameter) { 
    Method Body; 
    return data ; 
}
  • Explanation:

public static modifier.

The data type of the data returned after the return value type method operation has completed

If the method does not return a value, write void here, not return in the body of the method

Method NameIdentification used when calling a method
parameterComposed of data types and variable names separated by commas
Method BodyCode block to complete the function
returnIf the method operation is complete, data is returned to return the data to the caller
  • There are two definitions to make when defining a method
  1. Explicit return value type: Mainly clarify whether there is data return after the method operation is completed, and if not, write void; If so, write the corresponding data type
  2. Explicit parameters: mainly clarify the type and number of parameters
  • Note when calling methods:
  1. A method of type void, called directly
  2. Non-void type method, variable is recommended for receiving calls

3. Definition and use of methods with parameters

3.1 Method definition and invocation with parameters

  • Define Format

Parameter: 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 a method is defined, neither the data type nor the variable name in the parameter can be missing, and any program that is missing will fail

Use commas between multiple parameters when defining a method( ,)Separate
  • 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 or the program will fail

3.2 Formal and Actual Parameters

Formal parameter: A formal parameter used to define a method and to receive parameters passed by the caller. The parameter allocates the memory unit only when the method is called and releases the allocated memory unit after the method call ends. Therefore, the parameter is only valid inside the method, so changes to the reference object cannot affect outside the method.

For example:int number

Argument: is the actual parameter that is passed to the method when called. Arguments are pre-assigned before being passed to other methods. In this case, the numa, numb of the swap method is the parameter, and the a,b passed to the swap method is the argument

For example: 10 number

Note: Arguments can only be passed to a parameter during a value transfer call, and the value of a parameter cannot be inverted to an argument. During a function call, the value of the parameter changes, but the value of the parameter does not. In the mechanism of reference pass call, the address of the reference to the argument is actually passed to the parameter, so any change that occurs to the parameter will also occur to the argument variable.

  • Example
public class Test {    
    public static void main(String[] args) {
    	Integer a = 1;
    	Integer b = 2;
    	
    	System.out.println("a and b Original value:"+a+" "+b);    	
    	swap(a,b);    	
    	System.out.println("a and b Present value:"+a+" "+b);
    }
 
	private static void swap(Integer a, Integer b) {
		// TODO Auto-generated method stub		
	} 
}  

4. Definition and invocation of methods with return values

  • Define 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:

Return value after return when method definition matches data type on method definition, otherwise program will error

  • Call Format
Method Name ( parameter ) ; 
Data type variable name = Method Name ( parameter ) ;
  • Example:
isEvenNumber ( 5 ) ;
boolean flag = isEvenNumber ( 5 );
  • Be careful

The return value of a method is usually received with a variable, otherwise it will be meaningless.

5. Notes when using methods

  • Methods should be defined within classes, but they cannot be defined within methods. Cannot nest.

  • The order of method definitions does not matter.

  • Method definition will not be executed, if you want to execute, you must call: separate call, print call, assignment call.

  • If the method has a return value, you must write "return return return value;", you cannot have it.

  • The return value data after return must correspond to the return value type of the method.

  • For a method with no return value for void, the return value after return cannot be written, only return itself can be written.

  • The return of the last - row in the void method can be omitted from writing.

  • There can be more than one return statement in a method, but it must be guaranteed that only one return will be executed at the same time and that the two returns cannot be concatenated.

Example: Methods cannot be nested

public class MethodDemo { 
    public static void main(String[] args) { 
    }
    public static void methodOne() { 
        public static void methodTwo() { 
            // This will cause compilation errors!!! 
        } 
    } 
}

Example: void means no return value, return can be omitted or written separately without data

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); The return statement cannot be followed by data or code 
    } 
}

6. Method overload

If there are multiple methods in a class with the same name but different parameters, it is called method overload. If only one operation is required, having the same method name increases the readability of the program.

  • 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 
    } 
}

It is not difficult to see from the above code that the program needs to define a method for each summation case. If each method has a different name, it is difficult to tell which method should be called in which case.
To solve this problem, Java allows multiple methods with the same name to be defined in a class, but the type or number of parameters must be different, which is the overload of the method.

Be careful:

  1. Overload only corresponds to the definition of the method, not to its invocation, which refers to the standard format
  2. Overload identifies only the names and parameters of methods in the same class, not the return values, in other words, the return values cannot be used to determine whether the two methods constitute overloads.

7. Method parameter transfer

There are two ways to pass parameters to a method. Pass-by-value representation accepts the value provided by the caller; The call by reference representation accepts the variable address provided by the caller.

Notes include:

1. A method cannot modify a parameter of a basic data type (i.e., numeric or Boolean).

2. A method can change the state of an object (array) parameter.

3. A method cannot have an object parameter (array) refer to a new object.

Value transfer: When a method is called, the actual parameter passes its value to the corresponding formal parameter, and the function receives a copy of the original value. In this case, there are two equal basic types in memory, that is, the actual parameter and the formal parameter. The operation in the latter method is to modify the value of the parameter without affecting the value of the actual parameter.

Reference Passing: Also known as Address Passing, Address Passing. When a method is called, the reference to the actual parameter (address, not the value of the parameter) is passed to the corresponding formal parameter in the method. The function receives the memory address of the original value in the method execution. The parameter and the actual parameter content are the same, pointing to the same memory address. The operation of the reference in the method execution will affect the actual object.

Note: Similar basic packaging type classes such as String, Integer, Float, Double, Short, Byte, Long, Character. Because they themselves do not provide a way to change internal values, such as Integer having a value inside to record the value of the int base type, but they do not provide a way to modify it, and they are final and cannot be changed by regular means. So even though they are of reference type, they can be thought of as value-passing, which is only to say that in fact they are reference-passing and address-passing.

Example value transfer:

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 After method:" + number); 
    }
    public static void change(int number) { 
        number = 200;
    } 
}
  • Conclusion:

Parameters of the basic data type, changes in the form parameters, do not affect the actual parameters

  • The conclusion is based on:

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

Reference Passing Example:

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 After method:" + arr[1]);
    }
    public static void change(int[] arr) {
        arr[1] = 200;
    } 
}
  • Conclusion:

For parameters of reference type, changes in the form parameter affect the value of the actual parameter

  • The conclusion is based on:

A reference to a data type passes in an address value, which causes two references in memory to point to the same memory, so even if the method stack is used, the data in the stack memory is already the result of the change

Topics: Java Back-end J2EE