table of Contents
1. Definition of method
修饰符 返回值类型 方法名(参数类型 参数名){
***
方法体
***
return 返回值;
}
2. Several forms of method call
(1) The first
If the method has no return value or the calling program does not care about the return value of the method, the following format can be used:
方法名 (实参1, 实参2, ……)
(2) The second
If the calling program needs the return result of the method, the following format can be used:
变量 = 方法名(实参1, 实参2, ……)
(3) The third
For method calls with return values, the returned results can also be used directly in the program:
System.out.println("Add 2"+getSum(2, 4))
3. Code example
1.
public class Demo01 {
//main方法
public static void main(String[] args) {
int sum = add(1,2);
System.out.println(sum);
test();
}
//加法
public static int add(int a, int b){
return a+b;
}
public static void test() {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
2.
public class Demo02 {
public static int getSum (int x, int y){
if (x <= 0 || y <= 0 ){
return -1;
}return x+y;
}/*这样的程序对传入的参数值进行了检查控制;
许多程序错误都是由非法参数引起的*/
public static void main(String[] args) {
int sum = getSum(4, 5);
System.out.println("Add 1 = "+sum);
System.out.println("Add 2 = "+getSum(2, 4));
getSum(6, 10);
}
}
Tip: All methods in Java are contained in classes. The methods defined in a class in Java are also called methods of this class, and methods are methods.
4. Overloading of methods
5. The parameter transfer process of the method
6. Command line parameter transfer
Station B link: link
7. Variable parameters
1.
public class Demo04 {
public static void main(String[] args) {
Demo04 demo04 = new Demo04();
demo04.test(2,23,4,5,56,543);
}
public void test(int... i){
System.out.println(i[0]);
System.out.println(i[3]);
}
}
2.
public class Demo04 {
public static void main(String[] args) {
printMax(34,34,243.4);
printMax(new double[]{
1,2,3,54.5});
}
public static void printMax(double... numbers){
if (numbers.length == 0){
System.out.println("No argument passed!");
return;
}
double result = numbers[0];//排序
for (int i = 1; i < numbers.length; i++){
if (numbers[i] > result){
result = numbers[i];
}
}
System.out.println("The max value is "+result);
}
}