当前位置:网站首页>Methods, functions
Methods, functions
2022-07-28 17:53:00 【night_ du】
1、 Concept
Concept : A piece of code that implements a specific function , Can be used repeatedly .
2、 Definition

- Modifier :public 、static It's called a modifier
- return type :⽤ To illustrate the ⽅ Type of operation result . If you return other types , Compilation can go wrong
- ⽅ Legal name : It acts as a key ⽤ Time quote ⽤⽅ Identification of law
- Parameter list : stay ⽅ The law has been adjusted ⽤ when ⽤ Accept external communication ⼊ The variables of are called formal parameters, which are called formal parameters for short ,⽅ The number of formal parameters of method can be 0 A to
Multiple , Before each parameter ⾯ The data type to declare parameters is called parameter type ; Each parameter should ⽤ Comma separated . It's fine too ⼀ There are no parameters - ⽅ Dharma body : It is ⼀ A statement block , Of board ⾏ Specific function operation . For those with return value type ⽅ Law ,⽅ At the end of the Dharma body ⼀ The first sentence is
return keyword , Its work ⽤ It's a ⽅ The enforcement of law ⾏( operation ) The result goes back to ⽅ External law - return expression :return Is the key word , do ⽤ Yes, it will return after ⾯ The result of the expression is ⽅ The return value of the method . Pay attention to the expression
type , Must be with ⽅ Declared in the header “ Return type ” Match
grammar :
public static void Method name (){
// Method theme
}
Methods are defined inside the class , On main Method juxtaposition
demonstration :
public static void main(String[] args) {
xing();// call xing Method
System.out.println(" abed, I see a silver light ");
xing();
System.out.println(" The frost on the ground ");
xing();
System.out.println(" look at the bright moon ");
xing();
System.out.println(" Bow your head and think of your hometown ");
xing();
}
public static void xing() {
System.out.println("************");
}
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-g8TaNdkn-1645534383870)(F:\WP\BaiduNetdiskWorkspace\noteFile\JavaSE\6、 Method 、 function \ Method 、 function .assets\20210812135901407_2558.png)]](/img/65/f3469ac543d22a7b17f5f6e5623e6b.png)
3、 call
classification
Ginseng 、 No arguments 、 There is a return value 、 No return value
//⽆ ginseng ⽆ The return value of ⽅ Law public static void method1(){ System.out.println(" I am ⾃ entertainment ⾃ Happy "); } // Ginseng ⽆ The return value of ⽅ Law public static void method2(int a){ // Calculation a flat ⽅ System.out.println(a*a); } //⽆ Parameter with return value ⽅ Law public static long method3(){ // Get the current time long time = System.currentTimeMillis(); return time; } // With parameter and return value public static int method4(int a,int b){ // return a,b The median value is ⼤ the return a>b?a:b; }Call mode
- Call alone Methods are independent of other code , Perform functions independently
- Multi use inspection and maintenance methods
- Output call Only output the results , This call means nothing to us
- Assignment call There is a return value result , You can do the next step
- Call alone Methods are independent of other code , Perform functions independently
public static void main(String[] args) {
// Assignment tone ⽤
int c = multipy(14, 15);
System.out.println(c);
// Output modulation ⽤
print();
// Adjust separately ⽤
clear();
}
// Definition ⽅ Law , Calculate the product of two numbers
public static int multipy(int a, int b){
int count = a * b;
return count;
}
// Print statement function
public static void print(){
System.out.println(" wow , Beautiful ⼥....");
}
// System garbage cleaning function
public static void clear(){
for (int i = 0; i < 1000; i++) {
System.out.println(" System cleaning ....");
}
}
4、 benefits
Reduce code redundancy 、 Improve reusability , Readability , Maintainability , Facilitate division of labor and cooperation
5、 heavy load
Definition
There are multiple methods with the same name in a class , Methods with different parameter lists are called method overloading
parameter list
- The number of parameters is different
- Different parameter types
- The order of the parameters is different
public static void method(int i,double d){
}
// And the ⼀ individual ⽅ The number of parameters of method is different
public static void method(int i){
}
// And the ⼀ individual ⽅ The types of parameters of method are different
public static void method(String str,float f){
}
// And the ⼀ individual ⽅ The order of the parameters of the method is different
public static void method(double d,int i){
}
6、 Methods call each other memory graph
- Definition of stack
- Run methods and store local variables
- A stack is a tube with an opening at one end , Similar to badminton tube


Execute the process
When JVM When executing a method , Will put this method on the stack to run . When this method calls other methods ,JVM The new method will also be placed on the existing method in the stack for execution , When the method is finished , The method will be JVM Remove... From the stack , It's called a bomb stack .
7、 Method parameters
Most of the time , Data interaction is required between the method and the caller ; The caller must provide the necessary data , In order to make the method complete the corresponding function .
Parameter function : The parameters of the method can make the code function more flexible 、 Higher universality , Easy to modify and maintain .
Formal parameter and actual parameter
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Sl06PBIq-1645534383871)(F:\WP\BaiduNetdiskWorkspace\noteFile\JavaSE\6、 Method 、 function \ Method 、 function .assets\20210811163218018_14308-1631325505881.png)]](/img/66/742cfc30e48e6dda5c00476d45f7e5.png)
A single parameter uses
demand : On multiple calls xing When the method is used , You can print minus signs for different times
public static void main(String[] args) {
xing(5);
System.out.println(" abed, I see a silver light ");
xing(10);
System.out.println(" The frost on the ground ");
xing(2);
System.out.println(" look at the bright moon ");
xing(15);
System.out.println(" Bow your head and think of your hometown ");
xing(5);
}
public static void xing(int count) {
for (int i = 0; i <= count; i++) {
System.out.print("*");
}
System.out.println();
}

Multiple parameters use
demand : On multiple calls xing When the method is used , You can print symbols for different times
public static void main(String[] args) {
xing(5,"*");
System.out.println(" abed, I see a silver light ");
xing(10,"+");
System.out.println(" The frost on the ground ");
xing(2,"&");
System.out.println(" look at the bright moon ");
xing(15,"%");
System.out.println(" Bow your head and think of your hometown ");
xing(5,"@");
}
public static void xing(int count,String hao) {
for (int i = 0; i <= count; i++) {
System.out.print(hao);
}
System.out.println();
}
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-UNw7i0ii-1645534383872)(F:\WP\BaiduNetdiskWorkspace\noteFile\JavaSE\6、 Method 、 function \ Method 、 function .assets\20210812135930501_10877.png)]](/img/36/e23eb835e7e05409922e32499459c5.png)
Return value and return type
Concept : The returned result after the method is executed .
After method execution , In some cases, there is no need to return results ; In other cases, the result must be returned .
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-9I1cv0IF-1645534383873)(F:\WP\BaiduNetdiskWorkspace\noteFile\JavaSE\6、 Method 、 function \ Method 、 function .assets\20210811164548452_6969-1631325505881.png)]](/img/12/99b20a5b564d875ea2117c395dc4c2.png)
Example :
demand : Define methods , Calculate the sum of two integers , And return the result , stay main Print in .
public class work2 {
public static void main(String[] args) {
double add=countNum(51.1, 2);
System.out.println(add);
}
public static double countNum(double num1, double num2) {
double sum = num1 + num2;
return sum;
}
Definition countNum Method has two parameters , Let them add up , Use return Return the sum . By calling countNum Assign a value to double num1, double num2.
Each method has a return value ,if Statement and so on, each branch has a return value .
return In two ways :
Used in methods that have return value types :
return value;// Indicates the end of the current method , With a return value , Return to method call .
The application has no return value type (void) The methods of :
return;// Indicates the end of the current method , Return directly to the method call .
Three keywords
| keyword | effect |
|---|---|
| continue | End this cycle |
| break | End the cycle , The code after the loop continues to execute |
| return | End the whole method |
8、 Numbers as parameters 、 Return value
As a parameter
Arrays are passed as method parameters , The parameter passed is the memory address of the array
public static void main(String[] args) {
int[] arr = {
1, 3, 5, 7, 9 };
// transfer ⽤⽅ Law , Pass array
printArray(arr);
}
/* establish ⽅ Law ,⽅ Method to receive parameters of array type Into the ⾏ Traversal of array */
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}

As return value
Array as ⽅ The return value of the method , It returns the memory address of the array
public static void main(String[] args) {
// transfer ⽤⽅ Law , Receive the return value of the array
// Received memory address of array
int[] arr = getArray();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
/* establish ⽅ Law , The return value is an array type return Return the address of the array */
public static int[] getArray() {
int[] arr = {
1, 3, 5, 7, 9 };
// Return the address of the array , Return to the key ⽤ person
return arr;
}

⽅ When the parameters of the method are basic types , What's passed is the data value . ⽅ The parameters of the method are ⽤ Type , What is passed is the address value .
9、 Variable parameters
Definition
Method declaration in , Represents multiple parameters of the same type
matters needing attention
In the actual call , Pass in multiple arguments within a method , Virtual Opportunities automatically help us fill in variable parameters , Form an array
Example
public void method(String... strs){ for (int i = 0; i < strs.length; i++) { System.out.println(strs[i]); } } public static void main(String[] args) { Class class1 = new Class(); class1.method("⼩ bright ","⼩ red ","⼩ when "); }
10、 recursive
recursive
Definition
Recursion is dealing with regular problems , Call your own method again inside the method
Use scenarios
- When a problem can be split into multiple problems , The treatment methods of size problems are consistent , Method calls itself
- Routine problems that can be handled with loops , Can use recursive processing
Use
Exit must be set , Let each method return correctly , Cannot call infinitely
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-nO9s9kRk-1645534383873)(F:\WP\BaiduNetdiskWorkspace\noteFile\JavaSE\6、 Method 、 function \ Method 、 function .assets\20210811170808216_29312-1631325505882.png)]](/img/be/8a5843e61123b7754d7b31fd6ee9ae.png)
Factorial recursion
demand : Calculation 5 The factorial :5!=54321;
public static void main(String[] args) {
System.out.println(countNum(5));
}
public static int countNum(int n) {
int num = 1;
for (int i = 1; i <= n; i++) {
num = num * i;
}
return num;
}
Recursive computation ![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-E7CC5Nvi-1645534383874)(F:\WP\BaiduNetdiskWorkspace\noteFile\JavaSE\6、 Method 、 function \ Method 、 function .assets\20210811173010536_31649-1631325505882.png)]](/img/2e/0a4c660b53fe91318c7aab85316b72.png)
public static void main(String[] args) {
System.out.println(Five(5));
}
//5!=5*4! n yes 5,Four(n - 1) Return to Four=4
public static int Five(int n) {
return n * Four(n - 1); //5*4*3*2*1 n=5
}
public static int Four(int n) {
return n * Three(n - 1); //4*3*2*1 n=4
}
public static int Three(int n) {
return n * Two(n - 1); //3*2*1 n=3
}
public static int Two(int n) {
return n * one(n - 1); //2*1 n=2
}
public static int one(int n) {
return 1; //1 n=1
}
In fact, the factorial method has been repeated in writing , We extract the repeated part , The optimizer .
public static void main(String[] args) {
System.out.println(Factorial(5));
}
// Special factorial method
public static int Factorial(int n) {
// Set the exit of program recursion , Otherwise, a memory overflow error will occur
if (n == 1) {
return 1;
}
//5*4!, then Factorial(n - 1) Will call itself , So it becomes 4*3!, Always recursive
return n * Factorial(n - 1);
}
Factorial It's a special way to calculate factorials , Call itself automatically , Repeated recursion , But we need to consider the export of the program , That is to say n=1 Back when 1, End procedure , Can't make n=-1 Calculate it , Otherwise, there will be a memory overflow error .
ic void main(String[] args) {
System.out.println(Factorial(5));
}
// Special factorial method
public static int Factorial(int n) {
// Set the exit of program recursion , Otherwise, a memory overflow error will occur
if (n == 1) {
return 1;
}
//54!, then Factorial(n - 1) Will call itself , So it becomes 43!, Always recursive
return n * Factorial(n - 1);
}
Factorial It's a special way to calculate factorials , Call itself automatically , Repeated recursion , But we need to consider the export of the program , That is to say n=1 Back when 1, End procedure , Can't make n=-1 Calculate it , Otherwise, there will be a memory overflow error .
边栏推荐
- Database performance analysis and optimization (internal training materials of Aite future team)
- abstract、static、final
- PCA reports error in eigen (crossprod (t (x), t (x)), symmetric = true): 'x' has infinite value or missing value
- [阅读笔记] For:Object Detection with Deep Learning: The Definitive Guide
- IO的操作
- 编译原理学习笔记3(自上而下语法分析)
- Tips--SCI论文写作中的小技巧
- MySQL optimization summary
- Use of multithreading
- 2021 National Undergraduate data statistics and Analysis Competition
猜你喜欢

编译原理学习笔记2(语法分析介绍)

Collection集合

On the non recursive and recursive implementation of finding the nth Fibonacci number respectively

Generation and use of dynamic link library (error summary)

进程、线程、信号量和互斥锁

编译原理学习笔记1(编译原理概述与词法分析)

USB virtual serial port (CDC) limit speed test

Mmcv installation method

有奖征文 | 2022 云原生编程挑战赛征稿活动开启!

Database performance analysis and optimization (internal training materials of Aite future team)
随机推荐
[p5.js learning notes] basic knowledge of code drawing
[unity] three pictures let you understand the shadergraph editor
LeetCode--45. 跳跃游戏Ⅱ(贪心)
JVM performance tuning
编译原理学习笔记1(编译原理概述与词法分析)
电脑充不进去电的解决方法
数字滤波器(一)--IIR与FIR的基本结构与MATLAB实现
Pycharm connects to remote docker
1.4-dos
QT programming serial port assistant
禅道项目管理软件,敏捷开发团队不可或缺的工具
leetcode系统性刷题(一)-----链表、栈、队列、堆
如何使用IDEA将项目上传到码云
点云处理--voxel filter
ROS system installation
【机器学习笔记】Regularization : Ridge Regression(岭回归)
【Unity】Timeline学习笔记(七):自定义片段(Clip)
1.1-注释
2022 IDEA (学生邮箱认证)安装使用教程以及基础配置教程
IDEA报错Error running ‘Application‘ Command line is too long解决方案