当前位置:网站首页>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 .
边栏推荐
- ROS custom message and use
- 【Unity Tilemap】教程 | Basic、Rule Tile、Prefab Brush、Tilemap Collider
- leetcode系统性刷题(二)------贪心、回溯、递归
- Collection集合
- [阅读笔记] For Paper:R-CNN系列的三篇论文总结
- MySQL installation
- [p5.js actual combat] my self portrait
- 【p5.js学习笔记】局部变量(let)与全局变量(var)声明
- Please make sure you have the correct access rights and the repository exists.
- 【Unity】三张图让你看懂ShaderGraph编辑器
猜你喜欢

7-8 浪漫侧影(25分)建树+新解题思路
![[阅读笔记] For Paper:R-CNN系列的三篇论文总结](/img/1d/8b862ac66ea04d9371f64e35fc4396.png)
[阅读笔记] For Paper:R-CNN系列的三篇论文总结

USB virtual serial port (CDC) limit speed test

Visual object class introduces Pascal VOC dataset

Idea error running 'application' command line is too long solution

MySQL的安装

Factor in R

Arya professional web automated test platform

.net动态调用webservice的三种方式

abstract、static、final
随机推荐
ROS零散知识点及错误解决
mmdetection3d(2)---结果、log可视化
leetcode系统性刷题(四)-----哈希表与字符串
DOS command Daquan basic command + network common command
点云处理---kd-tree
LeetCode--45. 跳跃游戏Ⅱ(贪心)
【C语言进阶】——函数指针
How to install PS filter plug-in
【C语言进阶】——指针进阶[Ⅰ]
PS fast making full screen watermark
Point cloud processing - KD tree
Collection集合
内部类、常用类
【Unity Tilemap】教程 | Basic、Rule Tile、Prefab Brush、Tilemap Collider
【C语言进阶】——剖析入微数据在内存中的存储 【下】(浮点数存储)
Can‘t use an undefined value as an ARRAY reference at probe2symbol
[阅读笔记]-2 通过朴素贝叶斯模型学习机器学习分类
Branch and loop (for and do while)
MySQL详解
abstract、static、final