java常用API之System类

System中代表程序所在系统,提供了对应的一些系统属性信息,和系统操作。System类不能手动创建对象,因为构造方法被private修饰,阻止外界创建对象。System类中的都是static方法,类名访问即可。

常用方法:

currentTimeMillis() 获取当前系统时间与1970年01月01日00:00点之间的毫秒差值

exit(int status) 用来结束正在运行的Java程序。参数传入一个数字即可。通常传入0记为正常状态,其他为异常状态

gc() 用来运行JVM中的垃圾回收器,完成内存中垃圾的清除。

getProperty(String key) 用来获取指定(字符串名称)中所记录的系统属性信息

arraycopy方法,用来实现将源数组部分元素复制到目标数组的指定位置

System类的方法练习:

l  练习一:验证for循环打印数字1-9999所需要使用的时间(毫秒)

public static void main(String[] args) {
     long start = System.currentTimeMillis();
	for (int i=0; i<10000; i++) {
         System.out.println(i);
}
long end = System.currentTimeMillis();
System.out.println("共耗时毫秒:" + (end-start) );
}

l  练习二:将src数组中前3个元素,复制到dest数组的前3个位置上

复制元素前:src数组元素[1,2,3,4,5],dest数组元素[6,7,8,9,10]

复制元素后:src数组元素[1,2,3,4,5],dest数组元素[1,2,3,9,10]

public static void main(String[] args) {
int[] src = new int[]{1,2,3,4,5};
int[] dest = new int[]{6,7,8,9,10};
System.arraycopy( src, 0, dest, 0, 3);
代码运行后:两个数组中的元素发生了变化
src数组元素[1,2,3,4,5]
dest数组元素[1,2,3,9,10]
}

l  练习三:循环生成100-999之间的的三位数并进行打印该数,当该数能被10整除时,结束运行的程序

public static void main(String[] args){
     Random random = new Random();
	while(true){
    int number = random.nextInt(900)+100; //0-899 + 100
    if (nmumber % 10 == 0) {
        System.exit(0);
}
}
}

  

  

  

 

 

 

 

原文地址:https://www.cnblogs.com/lxx2014/p/9411350.html