Java常用类之【Math类、Random类、System类、Runtime类】

时间:2023-03-08 17:06:45

一、Math类

Math类

【绝对值】Math.abs();//返回对应类型的绝对值

【最大值和最小值】Math.max(int a, int b) ,Math.min(int a,int b);(其他类型都可以)

【立方根】Math.cbrt(double a) ,返回double类型

【求幂】Math.pow(double a, double b) (参数1:底数,参数2:指数)

【正平方根】Math.sqrt(double a)

【随机数[0,1)】random() 返回带正号的 double 值,该值大于等于 0.0 且小于 1.0

【取整】

ceil(double a) ,返回大于给定数的最小整数

floor(double a) ,返回小于给定数的最大整数

【四舍五入】

static int round(float a)

static long round(double a)

二、Random类(随机数类)

random类

【作用】用于生成随机数

创建对象:Random random = new Random();

Random类方法

调用方式:Random对象.方法

    【R>=0】nextInt()
【0=<R<=n】nextInt(int n)
【0=<R<1.0】nextFloat()
【0=<R<1.0】nextDouble()
【R为long类型的取值范围】nextLong()

三、System类

System类方法:

【清理内存】System.gc();// 促进垃圾回收器 起来回收垃圾

【退出程序】System.exit(0);// 正常退出程序 无论运行到哪个位置 都是直接退出程序

【系统当前时间】long l = System.currentTimeMillis();//返回以毫秒为单位的当前时间(从1970年到现在的毫秒数)

四、Runtime类

Runtime类特点:

Runtime 类实例使应用程序能够与其运行的环境相连接

Runtime是单例模式的

Runtime类常用方法:

【当前可用内存】long freeMemory() ;返回 Java 虚拟机中的空闲内存量

【创建对象】Runtime runtime = Runtime.getRuntime();//创建对象

【清理内存】runtime.gc();// 建议回收垃圾

查看gc()方法清理内存的效果:

System.out.println(runtime.freeMemory());//回收前的空闲内存

runtime.gc();// 建议回收垃圾

System.out.println(runtime.freeMemory());//回收后的空闲内存