1. Method (function) Introduction
Various languages have the concept of methods (some languages call them functions or processes).
method is used to encapsulate a specific logical function. such as performing a calculation or operation.
Methods can be repeatedly called in the program, the method can reduce code duplication, ease the maintenance of the program, conducive to team collaboration.
2. Definition of the method
Modifier return value type method name (parameter list) {
Method body;
}
- Parameter of the method: the data that is passed to the method at the time of the call, which needs to be processed by the method
- Methods can have parameters, can also have no parameters, have the parameter to make the method more flexible processing
- When you define a method, you need to declare the parameter variables required by the method
- When a method is called, the actual parameter value is passed to the parameter variable of the method, and the type and number of the passed parameter must be guaranteed to conform to the declaration of the method
- After the method call ends, you can return a data called the return value
- Method must specify the type of the return value at declaration time;
A. If the method does not need a return value, declare the return value type as void
B. If the method needs to return data, declare the return value type as a specific data type
- Return statement: Returned by a return statement, the function of the return statement is to end the method and return the data to the caller.
A.return value; 1) End method Execution 2) Returns the result to the caller
B.return; End the execution of the method (no return value or write return, the system will automatically add a return by default)
Case 1: Define a non-parametric method, output Hello World
public class Test {public static void main (string[] args) {myprint (); Call method}public static void Myprint () { //write method, with main function main sibling, cannot write main function inside System.out.println ("Hello world!"); return; Can not write}}//run result: Hello world!
Case 2: Defining a Parameter method, outputting two integers and
public class Test {public static void main (string[] args) {int sum = Add (5,10); There is a return value, you need to define the variable receive, the type is intSystem.out.println (sum);} public static int Add (int x,int y) {return x+y; Returns X+Y and}}//run results: 15
Introduction to Java Methods