How to define and use methods in Java
This article mainly shows you "how to define and use methods in Java". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to define and use methods in Java".
1. Concept
The "Method" in the Java language may also be called "Function" in other languages. For some complex code logic, if you want to reuse the code and "use it at any time", you can put the code in curly braces "{}" and give it a name. When using the code, just find the name and call it.
two。 Actual combat exercise
2.1 Test the method of incoming parameters and return values
Code
MethodDemo.java
Package cn.test.logan.day04;import java.util.ArrayList;public class MethodDemo {public int num1; public int num2; / / method: syntax used to encapsulate a logical / / definition method: public returns the value type method name () {/ / logic} public int getSum () {int sum = num1 + num2; return sum } / / method with no return value, using void to denote public void say () {System.out.println ("method with no return value at this time, ");} / / method with parameter but no return value, method with the same name, but with different parameter list, overloaded public void say (String param) {System.out.println ("my input parameter is:" + param) of the method. } / / methods with multiple parameters and no return value public void say (String param1,String param2) {System.out.println ("the first parameter entered is:" + param1); System.out.println ("the second parameter entered is:" + param2);} / / methods with parameters and return values public int getDiff (int aline int b) {int diff = a-b; return diff } / / is used to sort the ArrayList public static void sortForArrayList (ArrayList list) {for (int item0)