4.javase常用类之其他类

it2023-10-15  59

1 System类

1.1System类的概述

​ System类代表系统,是系统级的属性和控制方法都放置到该类的内部,位于java.lang包。

特点:

该类的构造器是private的,所以无法创建该类的对象,也无法实例化该类。其内部的成员变量和成员方法都是static的,所以也很方便的进行调用。

1.2成员变量及方法

1.2.1 成员变量

in:标准输入流(键盘输入)out:标准输出流(显示器)err:标准错误输出流(显示器)

1.2.2 成员方法

**native long currentTimeMills():**返回当前的计算机时间,返回值是于GMT1970年1月1日0时0分0秒所差毫秒数。**void exit(int status)😗*作用是退出程序,status为0表示正常退出,非零代表异常退出,可以在图形化界面中实现程序的退出。**void gc()😗*请求系统进行垃圾回收,至于是否立即执行,取决于系统中垃圾回收算法的实现以及系统执行时的情况。**String getProperty(String key)😗*获取系统中属性名为key的属性的对应的值。

常见如下:

属性名属性说明java.versionjava运行时环境版本java.homejava安装目录os.name操作系统的名称os.version操作系统的版本user.name用户的账号名称user.home用户的主目录user.dir用户当前的工作目录

1.2.3 简单使用

@Test public void testSystem(){ String javaVersion = System.getProperty("java.version"); System.out.println("java的version:" + javaVersion); String javaHome = System.getProperty("java.home"); System.out.println("java的home:" + javaHome); String osName = System.getProperty("os.name"); System.out.println("os的name:" + osName); String osVersion = System.getProperty("os.version"); System.out.println("os的version:" + osVersion); String userName = System.getProperty("user.name"); System.out.println("user的name:" + userName); String userHome = System.getProperty("user.home"); System.out.println("user的home:" + userHome); String userDir = System.getProperty("user.dir"); System.out.println("user的dir:" + userDir); }

2 Math类的使用

2.1 Math的特点

​ 位于java.lang包,提供了一系列静态方法用于科学计算,其方法的参数和返回值类型一般为double型。

2.2常见的方法

abs :绝对值acos,asin,atan,cos,sin,tan:三角函数qrt:平方根pow(double a,doble b) :a的b次幂log:自然对数exp :e为底指数max(double a,double b):求最大值min(double a,double b):求最小值random():返回0.0到1.0的随机数[0,1);求[a,b)=>random()*(b-a)+along round(double a): double型数据a转换为long 型(四舍五入)toDegrees(double angrad):弧度—> 角度toRadians(double angdeg):角度—>弧度

3 BigInteger和BigDecimal的使用

3.1 BigInteger类

3.1.1 出现的背景

​ Integer类作为int的包装类,能存储的最大整型值为2^31 -1,Long类也是有限的,最大为2^63 -1。如果要表示再大的整数,不管是基本数据类型还是他们的包装类都无能为力,更不用说进行运算了。因此BigInteger应运而生。

3.1.2BigInteger的特点

​ java.math包的BigInteger可以表示不可变的任意长度的整数。BigInteger提供所有Java的基本整数操作符的对应物,并提供 java.lang.Math的所有相关方法。另外,BigInteger还提供以下运算:模算术、GCD计算、质数测试、素数生成,位操作以及一些其他操作。

3.1.3 构造器

**BigInteger(String val):**根据字符串构建BigInteger对象。

3.1.4 常见方法

**public BigInteger abs():**返回此BigInteger的绝对值的BigInteger。**BigInteger add(BigInteger val):**返回其值为(this + val)的 BigInteger**BigInteger subtract(BigInteger val):**返回其值为(this - val) 的BigInteger**BigInteger multiply(BigInteger val):**返回其值为(this*val)的BigInteger**BigInteger divide(BigInteger val):**返回其值为(this / val)的BigInteger。整数相除只保留整数部分。**BigInteger remainder(BigInteger val):**返回其值为 (this % val)的BigInteger。**BigInteger[] divideAndRemainder(BigInteger val):**返回包含(this / val)后跟(this % val)的两个BigInteger的数组。**BigInteger pow(int exponent):**返回其值为(this exponent )的BigInteger。

3.2 BigDecimal类

3.2.1 出现背景

​ 一般的Float类和Double类可以用来做科学计算或工程计算,但在商业计算中到要求数字精度比较高,故用到java.math.BigDecimal类 。

3.2.2 特点

​ BigDecimal类支持不可变的、任意精度的有符号十进制定点数。

3.2.3 构造器

public BigDecimal(double val)public BigDecimal(String val)

3.2.4 常见方法

**public BigDecimal add(BigDecimal augend):**加法**public BigDecimal subtract(BigDecimal subtrahend):**减法**public BigDecimal multiply(BigDecimal multiplicand):**乘法**public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode):**除法

3.2.5 简单测试

@Test public void testBigInteger() { BigInteger bi = new BigInteger("1243324112312312312312312312312312312312312312"); BigDecimal bd = new BigDecimal("12435.351"); BigDecimal bd2 = new BigDecimal("11"); System.out.println(bi); // System.out.println(bd.divide(bd2)); //必须指定精度,此时四舍五入,否则会报错,例如上一个,此输出为:1130.486 System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP)); //自定义精度:1130.486454545454545 System.out.println(bd.divide(bd2, 15, BigDecimal.ROUND_HALF_UP)); }

4 包装类

4.1 包装类简述

​ 包装类(封装类):针对八种基本数据类型定义相应的引用数据类型–包装类(封装类)。

基本数据类型包装类byteByteshortShortintIntegerlongLongbooleanBooleancharCharacterfloatFloatdoubleDouble

4.2 基本数据类型,包装类,String三者之间的相互转换

基本数据类型–>包装类:调用包装类的构造器

包装类–>基本数据类型:调用包装类中xxxValue()。

基本数据类型,包装类–>String类型:①使用拼接符号②String.valueOf()

String类型–>基本数据类型,包装类:包装类.parseXxx();

4.3 自动装箱与自动拆箱

自动装箱:不需要使用构造器进行封装。

​ int num=10;

​ Integer in1=num;

自动拆箱:自动转化为int类型

​ Integer in2=new Integer(10);

​ int num2=in2;

​ 注:如果Boolean输入不是一个标准的“true”,则都认为是false。如果数字类型字符串的转换为包装类的时候,有可能报成NumberFormatException。

4.4 简单使用

@Test public void test01() { //基本数据类型-->包装类,调用包装类的构造器 int num=1; Integer n=new Integer(num); //包装类-->基本数据类型:调用包装类中xxxValue()。 int num2=new Integer(2).intValue(); num2+=1; System.out.println(num2); int num3=Integer.parseInt("20"); System.out.println(num3); Boolean boolean1=new Boolean("True12"); System.out.println(boolean1); }

4.5 面试题

1.自动装箱面试1

public void wrapperTest(){ Integer a = new Integer(3); Integer b=3; int c=3; Integer d=new Integer(3); //false:不同的对象引用 System.out.println(a==b); //true:a进行自动拆箱 System.out.println(a==c); //true:b进行自动拆箱 System.out.println(b==c); //false:不同的对象引用 System.out.println(a==d); Integer f1=100,f2=100,f3=200,f4=200; //true:没有超出缓存范围,使用了同一个引用 System.out.println(f1==f2); //false:超出了内部缓存的范围,使用了不同的引用 System.out.println(f3==f4); }

​ 解析:首先需要注意的是 f1、f2、f3、f4 四个变量都是 Integer 对象引用,所以下面的==运算比较的不是值而是引用。装箱的本质是什么呢?当我们给一个 Integer 对象赋一个 int 值的时候,会调用 Integer 类的静态方法 valueOf,如果看看 valueOf 的源代码就知道发生了什么。

//源码 public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } /** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as required by JLS. * * The cache is initialized on first usage. The size of the cache * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option. * During VM initialization, java.lang.Integer.IntegerCache.high property * may be set and saved in the private system properties in the * sun.misc.VM class. */ private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }

简单的说:如果使用自动装箱的功能,我们给一个Integer进行赋值的时候,会调用Integer的valueOf方法,判断他的值是否在-128 到 127 (有符号一个字节数表示范围)之间,如果在,那么不会 new 新的 Integer 对象,而是直接引用常量池中的 Integer 对象,如果超过了这个范围则会创建一个新的对象,将这个对象的引用赋值给我们的变量。所以上面的面试题中 f1 == f2 的结果是 true,而 f3 == f4 的结果是 false。

最新回复(0)