Java learning summary: 20

variable parameter

Syntax form:

[public | protected | private][static][final][abstract] 返回值类型 方法名称(参数类型...变量){
	[return[返回值];]
}

Example: Using variable parameters to define methods

package com.study.Demo;

public class Test6 {
    public static void main(String args[]){
    	//可变参数支持接收数组
        System.out.println(add(new int[]{1,2,3}));	//传递3个整型数据
        System.out.println(add(new int[]{10,20}));	//传递2个整型数据
        //或者使用","区分不同的参数,接收的时候还是数组
        System.out.println(add(1,2,3));	//传递3个参数
        System.out.println(add(10,20));	//传递2个参数
        System.out.println(add());	//不传递参数
    }
    //实现多个整型数据的相加操作
    public static int add(int...data){	//由于要接收多个整型数据,所以使用数组完成接收
        int sum=0;
        for(int x=0;x<data.length;x++){
            sum+=data[x];
        }
        return sum;	//多个整型数据相加结果
    }
}
//结果
//6
//30
//6
//30
//0

foreach loop

Foreach is an enhanced for loop operation, which can be used to simplify the output operation of array or collection data.

Syntax form:

for(数据类型 变量:数组 | 集合){
	//每一次循环会自动的将数组的内容设置给变量
}

Example: Use foreach loop to achieve output

package com.study.Demo;

public class Test7 {
    public static void main(String args[]){
        int data[]=new int[]{1,2,3,4,5};	//定义数组
        for(int x:data){	//循环次数由数组长度决定
        //每一次循环实际上都表示数组的角标增长,会取得没一个数组的内容,并且将其设置给x
            System.out.print(x+"、");	//x就是每一个数组元素的内容
        }
    }
}
//结果
//1、2、3、4、5、

Static import

If the methods defined in a certain class are all static methods, then other classes must use the import to import the required packages before using this class, and then use "class name. Method ()" to call.

Example:

package com.study.A;

public class MyMath {
    public static int add(int x,int y){
        return x+y;
    }
    public static int div(int x,int y){
        return x/y;
    }
}
package com.study.Demo;

import com.study.A.MyMath;
public class Test8 {
    public static void main(String args[]){
        System.out.println("加法操作:"+ MyMath.add(10,20));
        System.out.println("除法操作:"+MyMath.div(10,2));
    }
}
//结果
//加法操作:30
//除法操作:5

If you do not want the class name to appear when calling these methods, that is, you can call the static methods in different packages directly in the main method, then you can use the static import operation to complete.

Syntax form:

import static..*;

Example:

package com.study.Demo;
//将MyMath类中的全部static方法导入,这些方法就好比在主类中定义的static方法一样
import static com.study.A.MyMath.*;
public class Test8 {
    public static void main(String args[]){
    	//主要使用方法名称访问
        System.out.println("加法操作:"+ add(10,20));
        System.out.println("除法操作:"+ div(10,2));
    }
}
//结果
//加法操作:30
//除法操作:5
49 original articles published · Liked 25 · Visits 1527

Guess you like

Origin blog.csdn.net/weixin_45784666/article/details/104433741